<?php

class UnionCompetitionService extends AbstractService
{
    /**
     * @var UnionCompetitionService
     */
    private static $instance;

    /**
     * Get instance of UnionCompetitionService.
     *
     * @return UnionCompetitionService
     */
    public static function get()
    {
        if (!self::$instance) {
            self::$instance = new UnionCompetitionService();
        }
        return self::$instance;
    }

    /**
     * Construction.
     */
    protected function __construct()
    {
        parent::__construct();
    }

    /**
     * 处理创建时的逻辑
     *
     * @param int $userId
     * @return void
     */
    public function handleCreate($userId)
    {
    }

    /**
     * 处理登录时的逻辑
     * 1. 更新货架出售信息
     *
     * @param int $userId
     * @return void
     */
    public function handleLogin($userId)
    {
    }

    /**
     * 提供当前 service 数据
     *
     * @param int $userId
     * @param boolean $visitMode default false
     * @return array()
     */
    public function info($userId, $visitMode = false)
    {
        return [];
    }

    /**
     * 工会赛开关
     * @param $isOpen
     * @return bool|string
     */
    public function setSwitch($isOpen)
    {
        //验证是否为首次社团竞赛
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH,$isOpen);

        return true;
    }

    /**
     * 准备数据生成
     */
    public function prepareDataGeneration()
    {
        $testTime1 = time();
        error_log('******社团竞赛数据初始化开始时间：'.$testTime1.'***准确时间:'.date("Y-m-d H:i:s",$testTime1)."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
        if ($isOpen != 1){
            error_log('******社团竞赛系统没有开启！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }

        error_log('******社团竞赛数据初始化开始！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        //获取当前请求时间
        $serverTime = GameService::get()->getReqTime();
        //获取当前时间属于周几
        $weekDay = date("w",$serverTime);
        error_log('******社团赛校验时间******星期:'.$weekDay."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        //获取工会公用分组配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            error_log('******社团赛杂项配置表不存在******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }

        //获取当前时间属于周几
        $hour = (int)date("H",$serverTime);
        //验证开启时段正确   正式的时候需要开启000000
        if ($weekDay != $groupConfig['matchTime1']){
            error_log('******社团竞赛数据生成在每周3******timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }
        if ($weekDay == $groupConfig['matchTime1'] && $hour != 11){
            error_log('******社团竞赛初始化只会在每周3上午11点50执行******timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }

        //获取服务器所有的工会进行分组
        $serversConfigs = SzConfig::get()->loadAppConfig('database', 'MySql');
        $instance = new SzMySqlDb($serversConfigs[0]);
        $originalGuildArr = $instance->select("SELECT `id`  FROM `ft_guild_info` WHERE `num` >= ".$groupConfig['buddyNum']);
        $guildArr = array();
        if (!empty($originalGuildArr)){
            foreach ($originalGuildArr as $k=>$data){
                $guildArr[] = $data['id'];
            }
        }

        $guildsNum = count($guildArr);
        error_log('******社团竞赛公会数量为:'.$guildsNum."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        if (empty($guildArr) || $guildsNum == 0){
            error_log('******社团竞赛查询公会数量为0'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }
        //验证是否为首次社团竞赛
        $hasFirst = $redisDb->get(GameConst::CACHE_KEY_HAS_FIRST_UNION_COMPETITION);

        if ($_ENV['APP_ENV'] != 'DEV') {
            //  正式的时候需要开启000000
            $nextStartTime = $serverTime + 10 * 60 - 1;
            //数据结构准备
            $robGuildIdStart = 1;//机器人工会id，之后需要转换为负数以作区分
            $endTime = $nextStartTime + $groupConfig['matchTime2'];//当前赛事失效时间

            //设置各阶段时间
            $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_START_TIME, $nextStartTime);
            $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_END_TIME, $endTime);
            $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_SUSPENSION_TIME, $endTime - 86400 - 86400);
            $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_SETTLEMENT_TIME, $endTime - 3600);
        } else {
            //测试使用000000
            $nextStartTime = $serverTime + 10 * 60;
            $robGuildIdStart = 1;//机器人工会id，之后需要转换为负数以作区分
            $endTime = $nextStartTime + $groupConfig['matchTime2'];//当前赛事失效时间

            //设置各阶段时间
            $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_START_TIME, $nextStartTime);
            $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_END_TIME, $endTime);
            $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_SUSPENSION_TIME, $endTime - 30 * 60);
            $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_SETTLEMENT_TIME, $endTime - 20 * 60);
            //测试使用000000
        }

        if ($hasFirst != 1){//首次开启社团竞赛
            error_log('******社团竞赛首次开启！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            //设置已经举办了第一次社团竞赛标记
            $redisDb->set(GameConst::CACHE_KEY_HAS_FIRST_UNION_COMPETITION,1);
            $newStructureGuilds = $this->createDataByQuality($guildArr,$groupConfig,$robGuildIdStart,1,$guildsNum,$nextStartTime,$endTime,GameConst::UNION_COMPETITION_SILVER);
            $this->createOrUpdateLibrary(array(array(),$newStructureGuilds['guildGroupData'],array()),$serverTime,$endTime);
        }
        else{//非首次开启社团竞赛
            //晋级名额及降级名额
//                $up = $groupConfig['promotion'][0];
//                $down = $groupConfig['promotion'][1];

            $gup = $groupConfig['goldPromotion'][0];
            $gdown = $groupConfig['goldPromotion'][1];
            $sup = $groupConfig['silverPromotion'][0];
            $sdown = $groupConfig['silverPromotion'][1];
            $bup = $groupConfig['copperPromotion'][0];
            $bdown = $groupConfig['copperPromotion'][1];
            /**
             * @var GuildCompetitionLibraryVo $goldLibraryInfo
             * @var GuildCompetitionLibraryVo $silverLibraryInfo
             * @var GuildCompetitionLibraryVo $bronzeLibraryInfo
             */
            $goldLibraryInfo =  SzPersister::get()->getVo(GameConst::UNION_COMPETITION_GOLD, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);
            $silverLibraryInfo =  SzPersister::get()->getVo(GameConst::UNION_COMPETITION_SILVER, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);
            $bronzeLibraryInfo =  SzPersister::get()->getVo(GameConst::UNION_COMPETITION_BRONZE, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);

            if (!$goldLibraryInfo || !$silverLibraryInfo || !$bronzeLibraryInfo){
                error_log('******工会分组库数据丢失:******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                return;
            }
            //黄金小组调整
            $goldPreGuildArr = $this->shuntGroup($goldLibraryInfo,$gup,$gdown,$groupConfig,GameConst::UNION_COMPETITION_GOLD);
            //白银小组调整
            $silverPreGuildArr = $this->shuntGroup($silverLibraryInfo,$sup,$sdown,$groupConfig,GameConst::UNION_COMPETITION_SILVER);
            //青铜小组调整
            $bronzePreGuildArr = $this->shuntGroup($bronzeLibraryInfo,$bup,$bdown,$groupConfig,GameConst::UNION_COMPETITION_BRONZE);

            //进行工会重组
            if (!empty($silverPreGuildArr['toGold'])){//黄金赛事
                $goldGroupArr = array_merge($goldPreGuildArr['left'],$silverPreGuildArr['toGold']);
            }
            else{
                $goldGroupArr = $goldPreGuildArr['left'];
            }

            if (empty($goldPreGuildArr['toSilver']) && empty($bronzePreGuildArr['toSilver'])){//白银赛事
                $silverGroupArr = $silverPreGuildArr['left'];
            }
            else{
                $temp = array_merge($silverPreGuildArr['left'],$goldPreGuildArr['toSilver']);
                $silverGroupArr = array_merge($temp,$bronzePreGuildArr['toSilver']);
            }

            if (!empty($silverPreGuildArr['toBronze'])){//青铜赛事
                $bronzeGroupArr = array_merge($bronzePreGuildArr['left'],$silverPreGuildArr['toBronze']);
            }
            else{
                $bronzeGroupArr = $bronzePreGuildArr['left'];
            }

            //新参加的社团添加到青铜模块
            foreach ($guildArr as $key=>$value){
                if (!in_array($value,$goldGroupArr) && !in_array($value,$silverGroupArr) && !in_array($value,$bronzeGroupArr)){
                    $bronzeGroupArr[] = $value;
                }
            }

            if (empty($goldGroupArr)){
                error_log('******黄金分组库为空******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                return;
            }
            if (empty($silverGroupArr)){
                error_log('******白银分组库为空******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                return;
            }
            if (empty($bronzeGroupArr)){
                error_log('******青铜分组库为空******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                return;
            }

            error_log('******初始化【黄金分组】开始******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            $newGoldStructure = $this->createDataByQuality($goldGroupArr,$groupConfig,$robGuildIdStart,0,count($goldGroupArr),$nextStartTime,$endTime,GameConst::UNION_COMPETITION_GOLD);
            error_log('******初始化【黄金分组】结束******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            if (empty($newGoldStructure) || !$newGoldStructure || $newGoldStructure == null){
                error_log('******初始化黄金分组为空！！！！******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                return;
            }
            error_log('******初始化【白银分组】开始******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            $newSilverStructure = $this->createDataByQuality($silverGroupArr,$groupConfig,$robGuildIdStart,$newGoldStructure['hasLast'],count($silverGroupArr),$nextStartTime,$endTime,GameConst::UNION_COMPETITION_SILVER);
            error_log('******初始化【白银分组】结束******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            if (empty($newSilverStructure) || !$newSilverStructure || $newSilverStructure == null){
                error_log('******初始化白银分组为空！！！！******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                return;
            }
            error_log('******初始化【青铜分组】结束******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            $newBronzeStructure = $this->createDataByQuality($bronzeGroupArr,$groupConfig,$robGuildIdStart,$newSilverStructure['hasLast'],count($bronzeGroupArr),$nextStartTime,$endTime,GameConst::UNION_COMPETITION_BRONZE);
            error_log('******初始化【青铜分组】结束******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            if (empty($newBronzeStructure) || !$newBronzeStructure || $newBronzeStructure == null){
                error_log('******初始化青铜分组为空！！！！******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                return;
            }

            $this->createOrUpdateLibrary(array($newBronzeStructure['guildGroupData'],$newSilverStructure['guildGroupData'],$newGoldStructure['guildGroupData']),$nextStartTime,$endTime);
        }
        error_log('******社团竞赛初始化结束！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');

        $testTime2 = time();
        error_log('******社团竞赛初始化结束时间：'.$testTime2.'***准确时间:'.date("Y-m-d H:i:s",$testTime2)."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        error_log('******社团竞赛初始化使用时间：'.($testTime2-$testTime1).'秒'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');

        return;
    }

    /**
     * 设置工会竞赛库
     * @param $qualityGroup
     * @param $serverTime
     * @param $endTime
     * @throws SzException
     */
    public function createOrUpdateLibrary($qualityGroup,$serverTime,$endTime){
        error_log('******设置工会竞赛库开始！！！！:'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        //进行赛事品质组入库
        /**
         * @var GuildCompetitionLibraryVo $guildCompetitionLibraryInfo
         */
        foreach ($qualityGroup as $key=>$groupData){
            $makeString = '';
            //工会组数据结构调整
            if (!empty($groupData)){
                foreach ($groupData as $gid=>$guilds){
                    if ($makeString == ''){
                        $makeString = ($gid+1).':'.implode(',',$guilds);

                    }
                    else{
                        $makeString = $makeString.';'.($gid+1).':'.implode(',',$guilds);
                    }
                }
            }
            $guildCompetitionLibraryInfo = SzPersister::get()->getVo($key + 1, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);
            if (!$guildCompetitionLibraryInfo){
                $guildCompetitionLibraryInfo = new GuildCompetitionLibraryVo(
                    $key + 1,
                    $makeString,
                    $serverTime,
                    $serverTime,
                    $endTime,
                    true
                );
            }
            else{
                $guildCompetitionLibraryInfo->setGuildsByGroup($makeString);
                $guildCompetitionLibraryInfo->setUpdateTime($serverTime);
                $guildCompetitionLibraryInfo->setEndTime($endTime);
            }

            //更新数据
            SzPersister::get()->setVo($guildCompetitionLibraryInfo);
        }
        error_log('******设置工会竞赛库结束！！！！:'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
    }

    /**
     * 初始化数据总入口
     * @param $guildArr
     * @param $groupConfig
     * @param $robGuildIdStart
     * @param $groupStart
     * @param $guildsNum
     * @param $serverTime
     * @param $endTime
     * @param int $quality
     * @return array|void
     * @throws SzException
     */
    public function createDataByQuality($guildArr,$groupConfig,$robGuildIdStart,$groupStart,$guildsNum,$serverTime,$endTime,$quality=2){
        //已分配好赛事品质的所有工会进行小组分配【首次赛事都是白银。不传递赛事品质】
        $groupByRandom = $this->randomGroup($guildArr,$groupConfig,$robGuildIdStart,$groupStart,$guildsNum,$quality);
        if (empty($groupByRandom['guildGroupData'])){
            error_log('******公会随机分组为空:'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }
        else{
            //生成该赛事小组数据
            $this->createGroupData($groupByRandom,$quality,$serverTime,$endTime);
            //该赛事各社团竞赛公用数据生成
            $this->createGroupCommonData($groupByRandom,$quality,$serverTime,$endTime);
            //该赛事各社团竞赛任务生成
            $this->createGroupTaskData($groupByRandom,$quality,$groupConfig,$serverTime,$endTime);
        }

        return $groupByRandom;
    }

    /**
     * 纯随机分组
     * @param $guildArr
     * @param $groupConfig
     * @param $robGuildIdStart
     * @param $groupStart
     * @param $num
     * @param $quality
     * @return array
     */
    public function randomGroup($guildArr,$groupConfig,$robGuildIdStart,$groupStart,$num,$quality)
    {
        $groupByRandom = array();
        $total = 0;

        if ($num <= $groupConfig['guildNum']){
            $needAddNum = $groupConfig['guildNum'] - $num;
            if ($needAddNum != 0){//补充机器人工会ID
                for ($robGuildIdStart ; $robGuildIdStart <= $needAddNum ; $robGuildIdStart++){
                    $guildArr[] = -($robGuildIdStart + $quality*10);
                }
            }
            $groupByRandom[] = $guildArr;
            $total = 1;
            $groupNum = 1;
        }
        else{
            $groupNum = floor($num/$groupConfig['guildNum']);
            $leftNum = $num%$groupConfig['guildNum'];
            for ($i = $groupStart ; $i < $groupStart + $groupNum ; $i++){
                $guildKeyArr = array_rand($guildArr,$groupConfig['guildNum']);
                if (!empty($guildKeyArr)){
                    foreach ($guildKeyArr as $key=>$guildKey){
                        $groupByRandom[$i][] = $guildArr[$guildKey];
                        unset($guildArr[$guildKey]);
                    }
                }
            }
            $total = $groupNum;
            if (!empty($guildArr) && count($guildArr) == $leftNum && (($groupConfig['guildNum'] - $leftNum) != 0) && $leftNum != 0){
                foreach ($guildArr as $key=>$guildData){
                    $groupByRandom[$groupStart + $groupNum][] = $guildData;
                    unset($guildArr[$key]);
                }
                $needAddNum = $groupConfig['guildNum'] - $leftNum;
                if ($needAddNum != 0){//补充机器人工会ID
                    for ($robGuildIdStart ; $robGuildIdStart <= $needAddNum ; $robGuildIdStart++){
                        $groupByRandom[$groupStart + $groupNum][] =  -($robGuildIdStart + $quality*10);
                    }
                    $total = $groupNum + 1;
                }
            }
        }

        return array(
            'guildGroupData' => $groupByRandom,
            'groupNum' => $total,
            'hasLast' => $total + $groupStart,
        );
    }

    /**
     * 生成小组数据
     * @param $groupByRandom
     * @param $quality
     * @param $serverTime
     * @param $endTime
     * @throws SzException
     */
    public function createGroupData($groupByRandom,$quality,$serverTime,$endTime)
    {
        error_log('******生成小组数据开始！！！！:'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        /**
         * @var GuildGroupVo $guildGroupInfo
         */
        $realGroup = '';
        $robGroup = '';
        $endGroupRob = 0;

        foreach ($groupByRandom['guildGroupData'] as $gid=>$groupMem){
            $tempReal = array();
            $tempRob = array();
            //小组成员数据生成
            foreach ($groupMem as $key1=>$data){
                if ($data > 0){
                    $tempReal[] = $data;
                    //创建工会的记录数据
                    /**
                     * @var GuildCompetitionRecordVo $guildRecord
                     */
                    $guildRecord = SzPersister::get()->getVo($data, GameConst::ORM_NAME_UNION_COMPETITION_RECORD);
                    if ($guildRecord){
                        error_log('*****---真实玩家工会ID:'.$data.'的记录数据已创建-----*******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                    }
                    else{
                        $guildRecord = new GuildCompetitionRecordVo(
                            $data,
                            $gid+1,
                            $quality,
                            (int)date('Ymd',$serverTime),
                            0,
                            0,
                            0,
                            0,
                            1,
                            $serverTime,
                            $serverTime,
                            true
                        );
                        SzPersister::get()->setVo($guildRecord);
                        error_log('******成功创建小组--【group】:'.($gid+1).'---真实玩家工会ID:'.$data.'】的记录数据-----*******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                    }
                }
                else{
                    $tempRob[] = $data;
                }
            }
            //处理工会字符串
            if (!empty($tempReal)){
                if (count($tempReal) == 1){
                    $realGroup = (string)$tempReal[0];
                }
                else{
                    $realGroup = implode(',',$tempReal);
                }
            }

            if (!empty($tempRob)){
                if (count($tempRob) == 1){
                    $robGroup = (string)$tempRob[0];
                }
                else{
                    $robGroup = implode(',',$tempRob);
                }
                $endGroupRob = 1;
            }

            error_log('******创建小组--【group】:'.($gid+1).'---真实玩家工会字符串:'.$realGroup."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            error_log('******创建小组--【group】:'.($gid+1).'---机器人工会字符串:'.$robGroup."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            //小组数据生成
            $guildGroupInfo = SzPersister::get()->getVo($gid+1, GameConst::ORM_NAME_UNION_COMPETITION);
            if (!$guildGroupInfo){
                $guildGroupInfo = new GuildGroupVo(
                    $gid+1,
                    $quality,
                    $endGroupRob == 0 ? 0 : $endGroupRob,
                    json_encode($realGroup),
                    json_encode($robGroup),
                    $serverTime,
                    $serverTime,
                    $endTime,
                    true
                );
            }
            //更新数据
            SzPersister::get()->setVo($guildGroupInfo);
            error_log('******创建小组--【group】:'.($gid+1).'---成功'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        }
        error_log('******生成小组数据结束！！！！:'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
    }

    /**
     * 各社团竞赛公用数据生成
     * @param $groupByRandom
     * @param $quality
     * @param $serverTime
     * @param $endTime
     * @throws SzException
     */
    public function createGroupCommonData($groupByRandom,$quality,$serverTime,$endTime)
    {
        error_log('******各社团竞赛公用数据生成开始！！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        $robShowArr = array();
        //获取机器人配置表
        $configs = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_ROBS, null, true);
        foreach ($configs as $key=>$conf){
            if ($conf['leagueMatch'] == $quality){
                $robShowArr[] = $conf['indexId'];
            }
            if (count($robShowArr) == 9){
                break;
            }
        }
        if (empty($robShowArr)){
            error_log('******品质赛事机器人配置获取出错:******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }

        /**
         * @var GuildCompetitionVo $guildCompetition
         */
        foreach ($groupByRandom['guildGroupData'] as $gid=>$members){
            foreach ($members as $key=>$guildId){
                $isRob = $guildId < 0 ? 1 : 0;
                $robIndex = 0;
                if ($isRob){
                    $robIndex = $robShowArr[array_rand($robShowArr)];
                }
                //公共数据生成
                $guildCompetition = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
                if (!$guildCompetition){
                    $guildCompetition = new GuildCompetitionVo(
                        $guildId,
                        $gid + 1,
                        $quality,
                        0,
                        0,
                        0,
                        0,
                        0,
                        $isRob,
                        $robIndex,
                        0,
                        json_encode(''),
                        $serverTime,
                        $serverTime,
                        $endTime,
                        true
                    );
                    //更新数据
                    SzPersister::get()->setVo($guildCompetition);
                }
                error_log('******社团ID:'.$guildId.'公共数据生成成功***'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                if ($guildId > 0){
                    //记录真实工会赛事品质
                    StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $serverTime, array(
                        'clientData' => array(
                            'tid' => 'Module:unionCompetition|action:getQuality|',
                            'item' => $guildId.'&'.$quality,
                            'value' => 1
                        )
                    ));
                }
            }
        }
        error_log('******各社团竞赛公用数据生成结束！！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
    }

    /**
     * 各社团竞赛任务生成
     * @param $groupByRandom
     * @param $quality
     * @param $groupConfig
     * @param $serverTime
     * @param $endTime
     * @throws SzException
     */
    public function createGroupTaskData($groupByRandom,$quality,$groupConfig,$serverTime,$endTime)
    {
        error_log('******各社团竞赛任务生成开始！！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        $qualityTaskConf = array();
        $taskShowWeightArr = array();
        //获取任务配置表
        $canCreateNum = $groupConfig['taskNum'][$quality-1];
        $configs = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_TASKS, null, true);
        foreach ($configs as $key=>$conf){
            if ($conf['leagueMatch'] == $quality){
                $qualityTaskConf[$conf['indexId']] = $conf;
                $taskShowWeightArr[] = array('tid'=>$conf['indexId'],'weight'=>$conf['weights']);
            }
            if (count($qualityTaskConf) == $canCreateNum){
                break;
            }
        }

        if (empty($qualityTaskConf) || empty($taskShowWeightArr)){
            error_log('******品质赛事任务配置获取出错:******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }

        /**
         * @var GuildCompetitionTaskVoList $guildCompetitionTaskList
         * @var GuildCompetitionTaskVo $guildCompetitionTask
         */
        foreach ($groupByRandom['guildGroupData'] as $gid=>$members){
            foreach ($members as $key=>$guildId){
                //过滤机器人
                if ($guildId < 0){
                    continue;
                }
                //获取该工会的公共数据
                /**
                 * @var GuildCompetitionVo $guildCompetitionData
                 */
                $guildCompetitionData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
                if (!$guildCompetitionData){
                    error_log('******社团竞赛公共数据未生成******guildId:'.$guildId."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                    continue;
                }

                //生成该工会的任务数据
                /**
                 * @var GuildCompetitionTaskVoList $guildCompetitionTaskList
                 * @var GuildCompetitionTaskVo $guildCompetitionTask
                 */
                $guildCompetitionTaskList = SzPersister::get()->getVoList($guildId, GameConst::ORM_NAME_UNION_COMPETITION_TASK);
                if ($guildCompetitionTaskList->getListCount() == 0){
                    for ($pos = 1 ; $pos <= $canCreateNum ; $pos++){
                        $taskIndexId = $this->randomTaskIdByWeight($taskShowWeightArr)['tid'];
                        $taskConf = $qualityTaskConf[$taskIndexId];
                        if (empty($taskConf)){
                            error_log('******社团竞赛任务生成出错******taskIndexId:'.$taskIndexId."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                            continue;
                        }
                        $needItem = 0;
                        if ($taskConf['taskitems'] != '0'){
                            $items = explode(';',$taskConf['taskitems']);
                            $needItem = $items[array_rand($items)];
                        }

                        $needProcess = rand($taskConf['randomNum'][0],$taskConf['randomNum'][1]);
                        $timeRange = $needProcess*$taskConf['limitedTime'];
                        $guildCompetitionTask = new GuildCompetitionTaskVo(
                            $guildId,//工会id
                            $pos,//位置
                            $taskConf['indexId'],//任务索引
                            $needItem,//指定物品
                            $needProcess,//目标进度
                            $timeRange,//需求时间段内完成
                            0,//当前完成进度
                            0,//用户ID
                            0,//任务状态
                            0,//接任务时间
                            0,//cd时间
                            $serverTime,//创建时间
                            $serverTime,//更新时间
                            $endTime,//失效时间
                            true
                        );
                        $guildCompetitionTaskList->addElement($guildCompetitionTask);
                        $guildCompetitionTaskList->setElement($pos,$guildCompetitionTask);
                    }
                    SzPersister::get()->setVoList($guildCompetitionTaskList);
                }
                else{
                    error_log('******社团竞赛任务未删除******guildId:'.$guildId."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                    continue;
                }
            }
        }
        error_log('******各社团竞赛任务生成结束！！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
    }

    /**
     * 根据权重随机获取任务索引
     * @param $weighArr
     * @return mixed
     */
    public function randomTaskIdByWeight($weighArr){
        $weight = 0;
        $temp = array();
        foreach ($weighArr as $data){
            $weight += $data['weight'];
            for ($i=0;$i<$data['weight'];$i++){
                $temp[] = $data;
            }
        }
        $use = rand(0, $weight-1);
        return $temp[$use];
    }

    /**
     * 工会赛前分组
     * @param $libraryInfo
     * @param $up
     * @param $down
     * @param $groupConfig
     * @param $quality
     * @return array
     */
    public function shuntGroup($libraryInfo,$up,$down,$groupConfig,$quality)
    {
        //没有变动的工会数据【需要进行重新随机】
        $results = array();
        //变动的工会数据
        $toGold = array();
        $toSilver = array();
        $toBronze = array();
        //过度数组
        $temp = array();
        if ($libraryInfo){
            if ($libraryInfo->getGuildsByGroup() != ''){
                $oldGroup = explode(';',$libraryInfo->getGuildsByGroup());
                foreach ($oldGroup as $k=>$groupStr){
                    $times = 1;
                    $guildIdArr = explode(',',explode(':',$groupStr)[1]);
                    $gid = explode(':',$groupStr)[0];
                    if ($quality == GameConst::UNION_COMPETITION_GOLD && count($guildIdArr) < 7){//黄金赛事组内剩余6个工会，不用进行掉级
                        continue;
                    }
                    foreach ($guildIdArr as $key=>$guildId){
                        if ($quality == GameConst::UNION_COMPETITION_GOLD){//黄金赛事
                            if ($times > $groupConfig['guildNum'] - $down){
                                //后三个进入低级赛事
                                $toSilver[] = $guildId;
                                unset($guildIdArr[$key]);
                            }
                        }
                        if ($quality == GameConst::UNION_COMPETITION_SILVER){//白银赛事
                            if ($times <= $up){
                                //前三个进入高级赛事
                                $toGold[] = $guildId;
                                unset($guildIdArr[$key]);
                            }
                            if ($times > $groupConfig['guildNum'] - $down){
                                //后三个进入低级赛事
                                $toBronze[] = $guildId;
                                unset($guildIdArr[$key]);
                            }
                        }
                        if ($quality == GameConst::UNION_COMPETITION_BRONZE){//青铜赛事
                            if ($times <= $up){
                                //后三个进入低级赛事
                                $toSilver[] = $guildId;
                                unset($guildIdArr[$key]);
                            }
                        }
                        $times++;
                    }
                    $temp = array_merge($guildIdArr,$temp);
                }
                $results = $temp;
            }
            else{
                error_log('******公会竞赛品质为:【'.$quality.'】的工会库为空'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            }
        }

        //机器人清理
        if (!empty($results)){
            $results = $this->clearRobGuild($results);
        }
        if (!empty($toGold)){
            $toGold = $this->clearRobGuild($toGold);
        }
        if (!empty($toSilver)){
            $toSilver = $this->clearRobGuild($toSilver);
        }
        if (!empty($toBronze)){
            $toBronze = $this->clearRobGuild($toBronze);
        }

        return array(
            'left' => $results,
            'toGold' => $toGold,
            'toSilver' => $toSilver,
            'toBronze' => $toBronze,
        );
    }

    /**
     * 清理机器人工会
     * @param $guildArr
     * @return array
     */
    public function clearRobGuild($guildArr)
    {
        $res = array();
        foreach ($guildArr as $key=>$guild){
            if ($guild > 0){
                $res[] = $guild;
            }
        }
        return $res;
    }

    /**
     * 小时积分保护任务
     */
    public function hourDataProtect()
    {
        $testTime1 = time();
        error_log('******社团竞赛保护任务开始时间：'.$testTime1.'***准确时间:'.date("Y-m-d H:i:s",$testTime1)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
        if ($isOpen != 1){
            error_log('***社团竞赛系统没有开启***'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');
            return;
        }

        error_log("\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');
        //获取工会公用分组配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            error_log('***社团赛杂项配置表不存在***'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');
            return;
        }

        //获取当前请求时间
        $serverTime = GameService::get()->getReqTime();
        //获取当前时间属于周几
        $weekDay = date("w",$serverTime);
        //获取当前时间属于周几
        $hour = (int)date("H",$serverTime);
        if ($weekDay == $groupConfig['matchTime1'] - 1 || $weekDay == $groupConfig['matchTime1'] - 2){
            error_log('***社团竞赛保护任务在数据初始化前2天不执行【休赛期建不用执行】***timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');
            return;
        }

        if ($_ENV['APP_ENV'] != 'DEV') {
            //获取今天凌晨的时间戳   正式的时候需要开启000000
            $toDayStartTime = strtotime(date('Y-m-d'));
            $rangeTime1 = $toDayStartTime + $hour * 3600 - 60;
            $rangeTime2 = $toDayStartTime + $hour * 3600 + 60;

            $allGuilds = array();
            $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_HOUR_SEND, ($serverTime + 3600 + 4));
        } else {
            //测试使用000000
            $toDayStartTime = strtotime(date('Y-m-d'));
            $rangeTime1 = $serverTime - 60;
            $rangeTime2 = $serverTime + 60;

            $allGuilds = array();
            $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_HOUR_SEND, ($serverTime + 300 + 4));
            //测试使用000000
        }

        if ($serverTime > $rangeTime1 && $serverTime < $rangeTime2){
            //各社团竞赛公用数据进行数据保护【获取每个公会的基准积分进行加分】
            /**
             * @var GuildCompetitionLibraryVo $goldLibraryInfo
             * @var GuildCompetitionLibraryVo $silverLibraryInfo
             * @var GuildCompetitionLibraryVo $bronzeLibraryInfo
             */
            //获取本届各品质赛事参与的工会
            $goldLibraryInfo =  SzPersister::get()->getVo(GameConst::UNION_COMPETITION_GOLD, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);
            $silverLibraryInfo =  SzPersister::get()->getVo(GameConst::UNION_COMPETITION_SILVER, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);
            $bronzeLibraryInfo =  SzPersister::get()->getVo(GameConst::UNION_COMPETITION_BRONZE, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);
            //黄金品质汇入
            if ($goldLibraryInfo){
                if ($goldLibraryInfo->getGuildsByGroup() != ''){
                    $goldGroupData = explode(';',$goldLibraryInfo->getGuildsByGroup());
                    if (!empty($goldGroupData)){
                        foreach ($goldGroupData as $gid1=>$guilds1){
                            $allGuilds[] = $guilds1;
                        }
                    }
                    else{
                        error_log('***社团竞赛【黄金小组数据为空】***'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');
                    }
                }
            }
            else{
                error_log('***社团竞赛【黄金小组库数据不存在】***'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');
            }

            //白银品质汇入
            if ($silverLibraryInfo){
                if ($silverLibraryInfo->getGuildsByGroup() != ''){
                    $silverGroupData = explode(';',$silverLibraryInfo->getGuildsByGroup());
                    if (!empty($silverGroupData)){
                        foreach ($silverGroupData as $gid2=>$guilds2){
                            $allGuilds[] = $guilds2;
                        }
                    }
                    else{
                        error_log('***社团竞赛【白银小组数据为空】***'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');
                    }
                }
            }
            else{
                error_log('***社团竞赛【白银小组库数据不存在】***'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');
            }

            //青铜品质汇入
            if ($bronzeLibraryInfo){
                if ($bronzeLibraryInfo->getGuildsByGroup() != ''){
                    $bronzeGroupData = explode(';',$bronzeLibraryInfo->getGuildsByGroup());
                    if (!empty($bronzeGroupData)){
                        foreach ($bronzeGroupData as $gid3=>$guilds3){
                            $allGuilds[] = $guilds3;
                        }
                    }
                    else{
                        error_log('***社团竞赛【青铜小组数据为空】***'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');
                    }
                }
            }
            else{
                error_log('***社团竞赛【青铜小组库数据不存在】***'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');
            }


            if (empty($allGuilds) || count($allGuilds) == 0){
                error_log('***社团竞赛参与社团数量为0***'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');
                return;
            }

            //进行积分添加
            foreach ($allGuilds as $key=>$guildIds){
                $guildIds = explode(',',explode(':',$guildIds)[1]);
                foreach ($guildIds as $key1=>$guildId){
                    //获取工会的公共数据
                    /**
                     * @var GuildCompetitionVo $guildCompetitionData
                     */
                    $guildCompetitionData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
                    if (!$guildCompetitionData){
                        error_log('***社团ID为:【'.$guildId.'】---公共数据为空'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');
                        continue;
                    }

                    //赛事品质
                    $quality = $guildCompetitionData->getQuality();
                    //旗帜发送数量
                    $limitNum = $groupConfig['flagNum'][$quality - 1];
                    if ($guildId > 0){//玩家真是工会处理
                        if ($guildCompetitionData->getPointSpeed() == 0){
                            continue;
                        }
                        if ($guildCompetitionData->getParticipant() == '' || $guildCompetitionData->getParticipant() == null){
                            continue;
                        }
                        $participantArr = explode(',',json_decode($guildCompetitionData->getParticipant()));
                        $participantCount = count($participantArr);
                        if ($participantCount == 0){
                            continue;
                        }
                        error_log('***社团ID为:【'.$guildId.'】---积分添加开始---'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');
                        //加分
                        $needAddPoint = $guildCompetitionData->getPointSpeed();
                        $newPoint = $guildCompetitionData->getPoint() + $needAddPoint;
                        $guildCompetitionData->setPoint($newPoint);
                        $guildCompetitionData->setUpdateTime($serverTime);
                        //工会积分总数埋点
                        StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $serverTime, array(
                            'clientData' => array(
                                'tid' => 'Module:unionCompetition|action:guildPoint|',
                                'item' => $guildId.'&pointNum',
                                'value' => $newPoint
                            )
                        ));

                        //验证是否通过阶段积分
                        $nowStep = $guildCompetitionData->getStep();
                        $canSendReward = 0;
                        $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_HOUR_SEND_ITEM.$guildId,0);
                        if ($newPoint >= ($nowStep + 1)*$groupConfig['flagdistance'][$quality - 1]){
                            if ($nowStep + 1 <= $limitNum){
                                $newFlags = $guildCompetitionData->getFlags() + 1;
                                $guildCompetitionData->setFlags($newFlags);
                                $guildCompetitionData->setStep($nowStep + 1);
                                $canSendReward = 1;
                                $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_HOUR_SEND_ITEM.$guildId,1);
                                //工会旗帜总数埋点
                                StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $serverTime, array(
                                    'clientData' => array(
                                        'tid' => 'Module:unionCompetition|action:guildFlag|',
                                        'item' => $guildId.'&flagNum',
                                        'value' => $newFlags
                                    )
                                ));
                            }
                        }

                        //验证是否需要给公会中的玩家进行发奖
                        if ($canSendReward){
                            foreach ($participantArr as $key=>$uid){
                                //给参与者发奖
                                GameService::get()->handleEntity($uid,GameConst::UNION_COMPETITION_GET_FLAG, 1,  true);

                                //获取成员参赛数据
                                /**
                                 * @var GuildCompetitionMemberVo $guildCompetitionMemberData
                                 */
                                //获取玩家社团竞赛个人数据
                                $guildCompetitionMemberData =  SzPersister::get()->getVo($uid, GameConst::ORM_NAME_UNION_COMPETITION_MEMBER);
                                if ($guildCompetitionMemberData){
                                    $guildCompetitionMemberData->setEpicycleFlags($guildCompetitionMemberData->getEpicycleFlags() + 1);
                                    $guildCompetitionMemberData->setUpdateTime($serverTime);
                                    SzPersister::get()->setVo($guildCompetitionMemberData);
                                }

                                /**
                                 * 获取玩家商品数据
                                 * @var ModuleItemVoList $itemList
                                 */
                                $itemList = SzPersister::get()->getVoList($uid, ModuleItemConst::ORM_NAME_ITEM);
                                $flagItem = $itemList->getElementsByItemDefId(GameConst::UNION_COMPETITION_FLAG);
                                if (!$flagItem) {
                                    $flagNum = 0;
                                }
                                else{
                                    // 获取道具的拥有数量
                                    $flagNum = $itemList->getItemDefCount(GameConst::UNION_COMPETITION_FLAG);
                                }
                                //个人旗帜总数埋点
                                StatisticsService::get()->saveLog($uid, GameConst::LOG_TYPE_USER_ORBIT, array(
                                    'clientData' => array(
                                        'tid' => GameConst::UNION_COMPETITION_GET_FLAG.':'.$flagNum.'|',
                                        'item' => 'flag',
                                        'value' => 1
                                    )
                                ));
                            }
                        }
                    }
                    else{//机器人工会处理
                        //获取机器人配置
                        $robIndexId = $guildCompetitionData->getRobIndex();
                        if ($robIndexId == 0){
                            continue;
                        }
                        $robConfs =  SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_ROBS, $robIndexId, true);
                        //加分
                        $oldRobScore = $guildCompetitionData->getPoint();
                        $guildCompetitionData->setPoint($oldRobScore + rand($robConfs['robotScore'][0],$robConfs['robotScore'][1]));
                        $guildCompetitionData->setUpdateTime($serverTime);
                    }

                    //更新数据
                    SzPersister::get()->setVo($guildCompetitionData);
                    error_log('***社团ID为:【'.$guildId.'】---积分添加结束---'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');
                }
            }
            error_log("\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');

            $testTime2 = time();
            error_log('******社团竞赛保护任务结束时间：'.$testTime2.'***准确时间:'.date("Y-m-d H:i:s",$testTime2)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');
            error_log('******社团竞赛保护任务使用时间：'.($testTime2-$testTime1).'秒'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');

            return;
        }
        else{
            error_log('***社团竞赛保护任务整点开始时间容错1***rangeTime1:'.$rangeTime1.'***准确时间:'.date("Y-m-d H:i:s",$rangeTime1)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');
            error_log('***社团竞赛保护任务整点结束时间容错2***rangeTime2:'.$rangeTime2.'***准确时间:'.date("Y-m-d H:i:s",$rangeTime2)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');
            error_log('***社团竞赛保护任务不允许在整点之外的时间执行***timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');
            error_log('------------------------------------------------------'."\r\n"."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement-' . date('Y-m-d') . '.log');
            return;
        }
    }

    /**
     * 数据结算
     */
    public function dataSettlement(){
        $testTime1 = time();
        error_log('******社团竞赛数据结算开始时间：'.$testTime1.'***准确时间:'.date("Y-m-d H:i:s",$testTime1)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
        if ($isOpen != 1){
            error_log('******社团竞赛系统没有开启！！！'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
            return;
        }

        error_log('******社团竞赛数据结算开始！！！'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
        //获取杂项配置表配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            error_log('******社团赛杂项配置表不存在******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
            return;
        }

        //获取当前请求时间
        $serverTime = GameService::get()->getReqTime();
        //获取当前时间属于周几
        $weekDay = date("w",$serverTime);
        //获取当前时间属于周几
        $hour = (int)date("H",$serverTime);
        //正式的时候需要开启000000
        if ($weekDay != $groupConfig['matchTime1'] - 1){
            error_log('******社团竞赛数据结算只会在下一届数据初始化前一小时执行******timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
            return;
        }
        if ($weekDay == $groupConfig['matchTime1'] - 1 && $hour != 23){
            error_log('******社团竞赛数据结算只会在晚上11点30执行******timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
            return;
        }

        if ($_ENV['APP_ENV'] != 'DEV') {
            //获取今天凌晨的时间戳
            $toDayStartTime = strtotime(date('Y-m-d'));
            $rangeTime1 = $toDayStartTime + $hour * 3600 + 30 * 60 - 60;
            $rangeTime2 = $toDayStartTime + $hour * 3600 + 30 * 60 + 60;
        } else {
            //测试使用000000
            //获取今天凌晨的时间戳
            $toDayStartTime = strtotime(date('Y-m-d'));
            $rangeTime1 = $toDayStartTime + $hour * 3600 + 40 * 60 - 60;
            $rangeTime2 = $toDayStartTime + $hour * 3600 + 40 * 60 + 60;
            //测试使用000000
        }

        if ($serverTime > $rangeTime1 && $serverTime < $rangeTime2) {
            //黄金品质结算
            $goldSuc = $this->guildHistoryDataUpdateOrCreate(GameConst::UNION_COMPETITION_GOLD,$groupConfig,$serverTime);
            error_log('******黄金品质结算结果:【'.$goldSuc.'】'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
            //白银品质结算
            $silverSuc = $this->guildHistoryDataUpdateOrCreate(GameConst::UNION_COMPETITION_SILVER,$groupConfig,$serverTime);
            error_log('******白银品质结算结果:【'.$silverSuc.'】'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
            //青铜品质结算
            $bronzeSuc = $this->guildHistoryDataUpdateOrCreate(GameConst::UNION_COMPETITION_BRONZE,$groupConfig,$serverTime);
            error_log('******青铜品质结算结果:【'.$bronzeSuc.'】'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');

            error_log('******社团竞赛数据结算结束！！！'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
        }
        else{
            error_log('******社团竞赛数据超时！！！'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
        }

        $testTime2 = time();
        error_log('******社团竞赛数据结算结束时间：'.$testTime2.'***准确时间:'.date("Y-m-d H:i:s",$testTime2)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
        error_log('******社团竞赛数据结算使用时间：'.($testTime2-$testTime1).'秒'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');

        return;
    }

    /**
     * 数据记录
     * @throws SzException
     */
    public function saveGuildByGroupData()
    {
        $testTime1 = time();
        error_log('******上一届数据记录开始：'.$testTime1.'***准确时间:'.date("Y-m-d H:i:s",$testTime1)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
        if ($isOpen != 1){
            error_log('******系统没有开启！！！'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            return;
        }

        error_log('******上一届数据记录开始！！！！:'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
        //获取杂项配置表配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            error_log('******社团赛杂项配置不存在******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            return;
        }

        //获取当前请求时间
        $serverTime = GameService::get()->getReqTime();
        //获取当前时间属于周几
        $weekDay = date("w",$serverTime);
        //获取当前时间属于周几
        $hour = (int)date("H",time());
        //正式的时候需要开启000000
        if ($weekDay != $groupConfig['matchTime1']){
            error_log('******上一届数据记录只在每周3执行******timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            return;
        }
        if ($weekDay == $groupConfig['matchTime1'] && $hour != 11){
            error_log('******上一届数据记录只每周3上午11点10分执行******timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            return;
        }

//        //获取今天凌晨的时间戳
        $toDayStartTime = strtotime(date('Y-m-d'));
        $rangeTime1 = $toDayStartTime + $hour*3600 + 10*60 - 60;
        $rangeTime2 = $toDayStartTime + $hour*3600 + 10*60 + 60;

        if ($serverTime > $rangeTime1 && $serverTime < $rangeTime2) {
            //黄金品质结算
            $goldSuc = $this->guildRecordUpdateOrCreate(GameConst::UNION_COMPETITION_GOLD,$serverTime);
            error_log('******黄金记录结果:【'.$goldSuc.'】'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            //白银品质结算
            $silverSuc = $this->guildRecordUpdateOrCreate(GameConst::UNION_COMPETITION_SILVER,$serverTime);
            error_log('******白银记录结果:【'.$silverSuc.'】'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            //青铜品质结算
            $bronzeSuc = $this->guildRecordUpdateOrCreate(GameConst::UNION_COMPETITION_BRONZE,$serverTime);
            error_log('******青铜记录结果:【'.$bronzeSuc.'】'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');

            error_log('******上一届数据记录结束！！！'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
        }
        else{
            error_log('******上一届数据记录超时！！！'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
        }

        //清理各品质数据生成标记
        $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_GOLD_FLAG,0);
        $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_SILVER_FLAG,0);
        $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_BRONZE_FLAG,0);

        $testTime2 = time();
        error_log('******上一届数据记录结束时间：'.$testTime2.'***准确时间:'.date("Y-m-d H:i:s",$testTime2)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
        error_log('******上一届数据记录使用时间：'.($testTime2-$testTime1).'秒'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');

        return;
    }

    /**
     * 历史记录数据更新或者创建
     * @param $quality
     * @param $reqTime
     * @return bool
     * @throws SzException
     */
    public function guildRecordUpdateOrCreate($quality,$reqTime){
        error_log('******上一届数据记录*****品质赛事为:【'.$quality.'】的数据开始！！！！******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
        /**
         * @var GuildCompetitionLibraryVo $libraryInfo
         */
        //获取本届各品质赛事参与的工会
        $libraryInfo = SzPersister::get()->getVo($quality, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);
        $sortString = '';
        if ($libraryInfo){
            if ($libraryInfo->getGuildsByGroup() != ''){
                $guildStrArr = explode(';',$libraryInfo->getGuildsByGroup());
                foreach ($guildStrArr as $key=>$groupStr){
                    $guildScoreArr = array();
                    $guildsArr = explode(',',(explode(':',$groupStr)[1]));
                    $groupId = explode(':',$groupStr)[0];
                    if (!empty($guildsArr)){
                        foreach ($guildsArr as $key1=>$guildId){
                            //获取工会工会数据
                            /**
                             * @var GuildCompetitionVo $guildCompetitionData
                             */
                            $guildCompetitionData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
                            if (!$guildCompetitionData){
                                error_log('******社团ID为:【'.$guildId.'】------公共数据为空******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
                                $point = 0;
                                $person = 0;
                                $flagNum = 0;
                            }
                            else{
                                $point = $guildCompetitionData->getPoint();
                                $flagNum = $guildCompetitionData->getFlags();
                                if (json_decode($guildCompetitionData->getParticipant()) != ''){
                                    $person = count(explode(',',json_decode($guildCompetitionData->getParticipant())));
                                }
                                else{
                                    $person = 0;
                                }
                            }
                            $guildScoreArr[$key1]['gid'] = $guildId;
                            $guildScoreArr[$key1]['score'] = $point;
                            $guildScoreArr[$key1]['personNum'] = $person;
                            $guildScoreArr[$key1]['flags'] = $flagNum;
                        }

                        //历史数据进行更新
                        $scoreTemp = array();
                        if (!empty($guildScoreArr) && count($guildScoreArr) != 0){
                            error_log('******小组ID为:【'.$groupId.'】------历史数据开始建立或者更新******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
                            //对分数数组进行排序
                            foreach ($guildScoreArr as $k => $row) {
                                $scoreTemp[$k] = $row['score'];
                            }
                            array_multisort($scoreTemp, SORT_DESC, $guildScoreArr);

                            $gidStr = '';
                            $gold = '';
                            $silver = '';
                            $bronze = '';
                            $i = 1;
                            $create = false;
                            $update = false;
                            foreach ($guildScoreArr as $index=>$guildRecordData) {
                                //小组排名字符串制作
                                if ($gidStr == ''){
                                    $gidStr = $guildRecordData['gid'];
                                }
                                else{
                                    $gidStr = $gidStr.','.$guildRecordData['gid'];
                                }

                                //真实用户数据处理
                                if ($guildRecordData['gid'] > 0){
                                    //历史数据存储
                                    $scoreArr = array(1=>0,2=>0,3=>0);
                                    /**
                                     * @var GuildCompetitionHistoryVo $guildHistoryInfo
                                     */
                                    $guildHistoryInfo = SzPersister::get()->getVo($guildRecordData['gid'], GameConst::ORM_NAME_UNION_COMPETITION_HISTORY);
                                    if (!$guildHistoryInfo){
                                        error_log('******创建工会ID为:【'.$guildRecordData['gid'].'】的历史数据开始******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
                                        if ($i <= 3) {//排名前三的工会记录排名数据
                                            if ($quality == GameConst::UNION_COMPETITION_GOLD){
                                                $scoreArr[$i] = 1;
                                                $gold = implode(',',$scoreArr);
                                            }
                                            if ($quality == GameConst::UNION_COMPETITION_SILVER){
                                                $scoreArr[$i] =1;
                                                $silver = implode(',',$scoreArr);
                                            }
                                            if ($quality == GameConst::UNION_COMPETITION_BRONZE){
                                                $scoreArr[$i] =1;
                                                $bronze = implode(',',$scoreArr);
                                            }
                                        }
                                        else{
                                            $gold = $silver = $bronze = implode(',',array(1=>0,2=>0,3=>0));
                                        }

                                        $guildHistoryInfo = new GuildCompetitionHistoryVo(
                                            $guildRecordData['gid'],
                                            json_encode($gold),
                                            json_encode($silver),
                                            json_encode($bronze),
                                            $guildRecordData['score'],
                                            $reqTime,
                                            $reqTime,
                                            0,
                                            true
                                        );
                                        $create = true;
                                    }
                                    else{
                                        error_log('******更新工会ID为:【'.$guildRecordData['gid'].'】的历史数据开始******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
                                        if ($i <= 3) {//排名前三的工会记录排名数据
                                            if ($quality == GameConst::UNION_COMPETITION_GOLD){
                                                $temp = json_decode($guildHistoryInfo->getGold());
                                                if ($temp != ''){
                                                    $goldArr = explode(',',$temp);
                                                    $goldArr[$i - 1] = $goldArr[$i - 1] + 1;
                                                }
                                                else{
                                                    $scoreArr[$i] = 1;
                                                    $goldArr = $scoreArr;
                                                }
                                                $guildHistoryInfo->setGold(implode(',',$goldArr));
                                            }
                                            if ($quality == GameConst::UNION_COMPETITION_SILVER){
                                                $temp = json_decode($guildHistoryInfo->getSilver());
                                                if ($temp != ''){
                                                    $silverArr = explode(',',$temp);
                                                    $silverArr[$i - 1] = $silverArr[$i - 1] + 1;
                                                }
                                                else{
                                                    $scoreArr[$i] = 1;
                                                    $silverArr = $scoreArr;
                                                }
                                                $guildHistoryInfo->setSilver(implode(',',$silverArr));
                                            }
                                            if ($quality == GameConst::UNION_COMPETITION_BRONZE){
                                                $temp = json_decode($guildHistoryInfo->getBronze());
                                                if ($temp != ''){
                                                    $bronzeArr = explode(',',$temp);
                                                    $bronzeArr[$i - 1] = $bronzeArr[$i - 1] + 1;
                                                }
                                                else{
                                                    $scoreArr[$i] = 1;
                                                    $bronzeArr = $scoreArr;
                                                }
                                                $guildHistoryInfo->setBronze(implode(',',$bronzeArr));
                                            }
                                        }

                                        if ($guildHistoryInfo->getHighest() < $guildRecordData['score']){
                                            $guildHistoryInfo->setHighest($guildRecordData['score']);
                                        }
                                        $guildHistoryInfo->setUpdateTime($reqTime);
                                        $update = true;
                                    }
                                    SzPersister::get()->setVo($guildHistoryInfo);
                                    if ($create){
                                        error_log('******创建工会ID为:【'.$guildRecordData['gid'].'】的历史数据结束******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
                                    }
                                    if ($update){
                                        error_log('******更新工会ID为:【'.$guildRecordData['gid'].'】的历史数据结束******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
                                    }

                                    //创建工会的记录数据
                                    /**
                                     * @var GuildCompetitionRecordVo $guildRecord
                                     */
                                    $guildRecord = SzPersister::get()->getVo($guildRecordData['gid'], GameConst::ORM_NAME_UNION_COMPETITION_RECORD);
                                    if (!$guildRecord){
                                        $guildRecord = new GuildCompetitionRecordVo(
                                            $guildRecordData['gid'],
                                            $groupId,
                                            $quality,
                                            (int)date('Ymd',$reqTime),
                                            (int)date('Ymd',$reqTime),
                                            $guildRecordData['score'],
                                            $i,
                                            $guildRecordData['personNum'],
                                            1,
                                            $reqTime,
                                            $reqTime,
                                            true
                                        );
                                        error_log('******成功创建小组--【group】:'.($groupId).'---真实玩家工会ID:'.$guildRecordData['gid'].'】的记录数据-----*******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
                                    }
                                    else{
                                        $guildRecord->setGroupId($groupId);
                                        $guildRecord->setQuality($quality);
                                        $guildRecord->setInitializationData($guildRecord->getSettlement());
                                        $guildRecord->setSettlement((int)date('Ymd',$reqTime));
                                        $guildRecord->setLastPoint($guildRecordData['score']);
                                        $guildRecord->setRank($i);
                                        $guildRecord->setNumber($guildRecordData['personNum']);
                                        $guildRecord->setIsFirst(0);
                                        $guildRecord->setUpdateTime($reqTime);
                                    }
                                    SzPersister::get()->setVo($guildRecord);

//                                //社团竞赛数据埋点
//                                StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $reqTime, array(
//                                    'clientData' => array(
//                                        'tid' => 'Module:unionCompetition|action:getQuality|',
//                                        'item' => $guildRecordData['gid'].'&'.$quality,
//                                        'value' => 1
//                                    )
//                                ));
//                                StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $reqTime, array(
//                                    'clientData' => array(
//                                        'tid' => 'Module:unionCompetition|action:getTotalPoint|',
//                                        'item' => $guildRecordData['gid'].'&'.$guildRecordData['score'],
//                                        'value' => 1
//                                    )
//                                ));
//                                StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $reqTime, array(
//                                    'clientData' => array(
//                                        'tid' => 'Module:unionCompetition|action:getTotalFlag|',
//                                        'item' => $guildRecordData['gid'].'&'.$guildRecordData['flags'],
//                                        'value' => 1
//                                    )
//                                ));
//                                StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $reqTime, array(
//                                    'clientData' => array(
//                                        'tid' => 'Module:unionCompetition|action:getTotalNum|',
//                                        'item' => $guildRecordData['gid'].'&'.$guildRecordData['personNum'],
//                                        'value' => 1
//                                    )
//                                ));
                                }

                                $i++;
                            }

                            if ($sortString == ''){
                                $sortString = $groupId.':'.$gidStr;
                            }
                            else{
                                $sortString = $sortString.';'.$groupId.':'.$gidStr;
                            }

                            error_log('******小组ID为:【'.$groupId.'】------历史数据结束建立或者更新******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
                        }
                    }
                }

                //新排序字符串进行更新
                if ($sortString != ''){
                    $libraryInfo->setGuildsByGroup($sortString);
                }
                $libraryInfo->setUpdateTime($reqTime);
                SzPersister::get()->setVo($libraryInfo);
            }
            else{
                error_log('******社团竞赛数据结算*****品质赛事为:【'.$quality.'】的参与工会为空******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            }
        }
        else{
            error_log('******社团竞赛数据结算*****品质赛事为:【'.$quality.'】的工会库不存在******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
        }

        error_log('******社团竞赛数据结算*****品质赛事为:【'.$quality.'】的数据结束！！！！******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
        return true;
    }


    /**
     * 历史数据更新或者创建
     * @param $quality
     * @param $groupConfig
     * @param $reqTime
     * @return bool
     * @throws SzException
     */
    public function guildHistoryDataUpdateOrCreate($quality,$groupConfig,$reqTime){
        error_log('******社团竞赛数据结算*****品质赛事为:【'.$quality.'】的数据开始！！！！******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
        /**
         * @var GuildCompetitionLibraryVo $libraryInfo
         */
        //获取本届各品质赛事参与的工会
        $libraryInfo = SzPersister::get()->getVo($quality, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);
        if ($libraryInfo){
            if ($libraryInfo->getGuildsByGroup() != ''){
                $guildStrArr = explode(';',$libraryInfo->getGuildsByGroup());
                foreach ($guildStrArr as $key=>$groupStr){
                    $guildsArr = explode(',',(explode(':',$groupStr)[1]));
                    $groupId = explode(':',$groupStr)[0];
                    if (!empty($guildsArr)){
                        foreach ($guildsArr as $key1=>$guildId){
                            if ($guildId < 0){
                                //删除公共数据
                                /* @var GuildCompetitionModel $guildCompetitionRobModel
                                 */
                                //获取工会工会数据
                                /**
                                 * @var GuildCompetitionVo $guildCompetitionRobData
                                 */
                                $guildCompetitionRobData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
                                if ($guildCompetitionRobData){
                                    error_log('******社团ID为:【'.$guildId.'】------删除机器人数据开始******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
                                    $guildCompetitionRobModel = SzPersister::get()->getModel(GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
                                    $guildCompetitionRobData = $guildCompetitionRobModel->retrieve(null, $guildId);
                                    $guildCompetitionRobModel->deleteVoCache($guildCompetitionRobData);
                                    $guildCompetitionRobModel->delete($guildCompetitionRobData);
                                    error_log('******社团ID为:【'.$guildId.'】------删除机器人数据数据结束******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
                                }
                                continue;
                            }

                            //获取工会工会数据
                            /**
                             * @var GuildCompetitionVo $guildCompetitionData
                             */
                            $guildCompetitionData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
                            if (!$guildCompetitionData){
                                error_log('******社团ID为:【'.$guildId.'】------公共数据为空******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
                                continue;
                            }

                            //删除参与者数据
                            error_log('******社团ID为:【'.$guildId.'】------删除参与者数据开始******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
                            if (json_decode($guildCompetitionData->getParticipant()) != ''){
                                $participantArr = explode(',',json_decode($guildCompetitionData->getParticipant()));
                                if (!empty($participantArr) && count($participantArr) != 0){
                                    foreach ($participantArr as $uid){
                                        /**
                                         * @var GuildCompetitionMemberVo $guildCompetitionMemberData
                                         */
                                        //获取玩家社团竞赛个人数据删除
                                        $guildCompetitionMemberData =  SzPersister::get()->getVo($uid, GameConst::ORM_NAME_UNION_COMPETITION_MEMBER);
                                        if ($guildCompetitionMemberData){
                                            /* @var GuildCompetitionMemberModel $guildCompetitionPersonModel
                                             */
                                            $guildCompetitionPersonModel = SzPersister::get()->getModel(GameConst::ORM_NAME_UNION_COMPETITION_MEMBER);
                                            $guildCompetitionMemberData = $guildCompetitionPersonModel->retrieve(null, $uid);
                                            $guildCompetitionPersonModel->deleteVoCache($guildCompetitionMemberData);
                                            $guildCompetitionPersonModel->delete($guildCompetitionMemberData);
                                        }
                                        //删除所拥有的临时头像框
                                        $this->clearHeadFrameData($uid,$groupConfig,$quality,$reqTime);
                                    }
                                }
                            }
                            else{
                                error_log('******社团ID为:【'.$guildId.'】------没有参与者参与本届工会竞赛******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
                            }
                            error_log('******社团ID为:【'.$guildId.'】------删除参与者数据结束******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');

                            //删除工会任务数据
                            /**
                             * @var GuildCompetitionTaskVoList $guildCompetitionTaskList
                             * @var GuildCompetitionTaskVo $guildCompetitionTask
                             */
                            error_log('******社团ID为:【'.$guildId.'】------删除工会任务数据开始******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
                            $guildCompetitionTaskList = SzPersister::get()->getVoList($guildId, GameConst::ORM_NAME_UNION_COMPETITION_TASK);
                            if ($guildCompetitionTaskList->getListCount() != 0){
                                foreach ($guildCompetitionTaskList->toArray() as $key3 => $taskData) {
                                    $guildCompetitionTaskList->deleteElement($taskData['pos'], false);
                                }
                            }
                            SzPersister::get()->setVoList($guildCompetitionTaskList);
                            error_log('******社团ID为:【'.$guildId.'】------删除工会任务数据结束******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');

                            //删除公共数据
                            /* @var GuildCompetitionModel $guildCompetitionModel
                             */
                            error_log('******社团ID为:【'.$guildId.'】------删除公共数据数据开始******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
                            $guildCompetitionModel = SzPersister::get()->getModel(GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
                            $guildCompetitionData = $guildCompetitionModel->retrieve(null, $guildId);
                            $guildCompetitionModel->deleteVoCache($guildCompetitionData);
                            $guildCompetitionModel->delete($guildCompetitionData);
                            error_log('******社团ID为:【'.$guildId.'】------删除公共数据数据结束******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
                        }

                        //删除小组数据
                        error_log('******小组ID为:【'.$groupId.'】------删除小组数据开始******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
                        /**
                         * @var GuildGroupVo $guildGroupInfo
                         */
                        $guildGroupInfo = SzPersister::get()->getVo($groupId, GameConst::ORM_NAME_UNION_COMPETITION);
                        if ($guildGroupInfo){
                            /* @var GuildGroupModel $guildGroupModel
                             */
                            $guildGroupModel = SzPersister::get()->getModel(GameConst::ORM_NAME_UNION_COMPETITION);
                            $guildGroupInfo = $guildGroupModel->retrieve(null, $groupId);
                            $guildGroupModel->deleteVoCache($guildGroupInfo);
                            $guildGroupModel->delete($guildGroupInfo);
                        }
                        error_log('******小组ID为:【'.$groupId.'】------删除小组数据结束******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
                    }
                }
            }
            else{
                error_log('******社团竞赛数据结算*****品质赛事为:【'.$quality.'】的参与工会为空！！！！******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
            }
        }
        else{
            error_log('******社团竞赛数据结算*****品质赛事为:【'.$quality.'】的工会库不存在******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
        }

        error_log('******社团竞赛数据结算*****品质赛事为:【'.$quality.'】的数据结束！！！！******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionDataSettlement.log');
        return true;
    }

    /**
     * 获取玩家自己的公会赛信息
     * @param $userId
     * @param $guildId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function getCompetitionInfo($userId,$guildId,$reqTime)
    {
        $res = array(
            'code' => 0,
            'guildMatch' => array(),
            'guild' => array(),
            'join' => 0
        );

        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        //白名单允许进入
        if (!in_array($userId,GameConst::UNION_COMPETITION_USERID)){
            //验证社团竞赛系统是否开启
            $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
            if ($isOpen != 1){
                $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//开关没有开启
                return $res;
            }
        }

        //获取各个时间段
        $rStartTime = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_START_TIME);
        if ($rStartTime == 0 || $rStartTime == null || $rStartTime == ''){
            $rStartTime = 0;
        }
        $rEndTime = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_END_TIME);
        if ($rEndTime == 0 || $rEndTime == null || $rEndTime == ''){
            $rEndTime = 0;
        }
        $rSuspensionTime = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SUSPENSION_TIME);
        if ($rSuspensionTime == 0 || $rSuspensionTime == null || $rSuspensionTime == ''){
            $rSuspensionTime = 0;
        }
        $rSettlementTime = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SETTLEMENT_TIME);
        if ($rSettlementTime == 0 || $rSettlementTime == null || $rSettlementTime == ''){
            $rSettlementTime = 0;
        }
        $rRewardTime = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_HOUR_SEND);
        if ($rRewardTime == 0 || $rRewardTime == null || $rRewardTime == ''){
            $rRewardTime = 0;
        }

        $res['guildMatch'] = array(
            'id' => (int)date('Ymd',$rStartTime),
            'startTime' => $rStartTime,
            'finishTime' => $rSuspensionTime,
            'countTime' => $rSettlementTime,
            'endTime' => $rEndTime,
            'nextRewardTime' => $rRewardTime
        );

        if ($reqTime >= $rStartTime && $reqTime < $rSettlementTime){
            $canShow = 0;
            //获取玩家工会是否可参赛本届社团竞赛
            /**
             * @var GuildCompetitionLibraryVo $guildCompetitionLibrary
             */
            for($i = 1; $i <= 3; $i++){
                $guildCompetitionLibrary = SzPersister::get()->getVo($i, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);
                if ($guildCompetitionLibrary){
                    if ($guildCompetitionLibrary->getGuildsByGroup() != ''){
                        $groupData = explode(';',$guildCompetitionLibrary->getGuildsByGroup());
                        if (!empty($groupData)){
                            foreach ($groupData as $gid=>$guilds){
                                if (in_array($guildId,explode(',',explode(':',$guilds)[1]))){
                                    $canShow = 1;
                                }
                            }
                        }
                    }
                    else{
                        continue;
                    }
                }
            }

            if ($canShow == 0){
                return $res;
            }

            //获取玩家参与赛事公用配置
            $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
            if (!$groupConfig || empty($groupConfig)){
                return $res;
            }

            //获取工会的公共数据
            /**
             * @var GuildCompetitionVo $guildCompetitionData
             */
            $guildCompetitionData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
            if (!$guildCompetitionData){
                return $res;
            }

            //时间验证
            $startTime = $guildCompetitionData->getCreateTime();
            $endTime = $guildCompetitionData->getEndTime();
            if ($reqTime < $startTime || $reqTime > $endTime){
                return $res;
            }

            $res['guild'] = $this->competitionFormatData($guildId,$guildCompetitionData);

            //获取工会所有参赛人员
            $personStr = json_decode($guildCompetitionData->getParticipant());
            if ($personStr != ''){
                $guildMembers = explode(',',$personStr);
                //发放旗帜给每个社员
                foreach ($guildMembers as $uid){
                    if ($uid == $userId){
                        $res['join'] = 1;
                        break;
                    }
                }
            }

            if ($_ENV['APP_ENV'] != 'DEV') {
                //正式的时候需要开启000000
                $res['guildMatch'] = array(
                    'id' => (int)date('Ymd', $startTime),
                    'startTime' => $startTime,
                    'finishTime' => $endTime - 86400 - 86400,
                    'countTime' => $endTime - 3600 + 2,
                    'endTime' => $endTime,
                    'nextRewardTime' => $rRewardTime
                );
            } else {
                //测试使用
                $res['guildMatch'] = array(
                    'id' => (int)date('Ymd', $startTime),
                    'startTime' => $startTime,
                    'finishTime' => $endTime - 30 * 60,
                    'countTime' => $endTime - 20 * 60 + 2,
                    'endTime' => $endTime,
                    'nextRewardTime' => $rRewardTime
                );
            }
        }

        if ($_ENV['APP_ENV'] != 'DEV') {
            //正式的时候需要开启000000
            if ($reqTime < $rStartTime && $reqTime >= $rStartTime - 15 * 60) {
                $res['guildMatch'] = array(
                    'id' => (int)date('Ymd', $rStartTime),
                    'startTime' => $rStartTime - 7 * 86400,
                    'finishTime' => $rStartTime - 86400 - 86400,
                    'countTime' => $rStartTime - 3600,
                    'endTime' => $rStartTime,
                    'nextRewardTime' => $rStartTime + 5,
                );
            }
        } else {
            //测试使用
            if ($reqTime < $rStartTime && $reqTime >= $rStartTime - 10 * 60) {
                $res['guildMatch'] = array(
                    'id' => (int)date('Ymd', $rStartTime),
                    'startTime' => $rStartTime - 3600,
                    'finishTime' => $rStartTime - 30 * 60,
                    'countTime' => $rStartTime - 20 * 60,
                    'endTime' => $rStartTime,
                    'nextRewardTime' => $rStartTime + 4,
                );
            }
        }

        return $res;
    }

    /**
     * 获取玩家社团赛任务列表
     * @param $userId
     * @param $guildId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function getCompetitionTaskAndUser($userId,$guildId,$reqTime)
    {
        $res = array(
            'code' => 0,
            'tasks' => array(),
            'self' => array()
        );

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        //白名单允许进入
        if (!in_array($userId,GameConst::UNION_COMPETITION_USERID)){
            $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
            if ($isOpen != 1){
                $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//开关没有开启
                return $res;
            }
        }

        //获取玩家参与赛事公用配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['CONFIG_NOT_EXIST'];//配置不存在
            return $res;
        }

        //结算时刻请求返回
        $canRequest = $this->checkLastHour($groupConfig,$reqTime);
        if (!$canRequest){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//下一届未开启
            return $res;
        }

        //获取玩家该赛季数据
        $userData = $this->getUserCompetitionData($userId,$reqTime,$reqTime,0);
        if (empty($userData)){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_97'];//社团赛事玩家数据错误
            return $res;
        }

        $res['self'] = $userData;

        //获取工会的公共数据
        /**
         * @var GuildCompetitionVo $guildCompetitionData
         */
        $guildCompetitionData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
        if (!$guildCompetitionData){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_95'];//社团赛事公共数据生成失败
            return $res;
        }
        //时间验证
        $startTime = $guildCompetitionData->getCreateTime();
        $endTime = $guildCompetitionData->getEndTime();
        if ($reqTime <= $startTime || $reqTime >= $endTime){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_98'];//不在社团竞赛循环时间内
            return $res;
        }

        //获取已经生成的工会任务列表
        /**
         * @var GuildCompetitionTaskVoList $guildCompetitionTaskList
         * @var GuildCompetitionTaskVo $guildCompetitionTask
         */
        $guildCompetitionTaskList = SzPersister::get()->getVoList($guildId, GameConst::ORM_NAME_UNION_COMPETITION_TASK);
        if (!$guildCompetitionTaskList){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_96'];//社团赛事工会任务数据生成失败
            return $res;
        }
        $taskDatas = array();
        //任务数据整理
        /**
         * @var GuildCompetitionMemberVo $guildCompetitionMemberData
         */
        foreach ($guildCompetitionTaskList->toArray() as $key=>$taskData){
            //获取每个任务的数据
            $guildCompetitionTask = $guildCompetitionTaskList->getElement($taskData['pos'],false);
            if (!$guildCompetitionTask){
                continue;
            }
            //获得单个任务的配置文件
            $taskConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_TASKS, $taskData['taskId'], true);
            $uid = $guildCompetitionTask->getUserId();
            if ($uid != 0
                && $guildCompetitionTask->getState() == 1
                && $guildCompetitionTask->getHandleTime() + $guildCompetitionTask->getTimeRange() < $reqTime)
            {//进行任务重置
                //获取玩家所属工会的赛事品质
                $quality = $guildCompetitionData->getQuality();
                $randomTaskConf = $this->getRandomTaskConf($quality);
                if ($randomTaskConf['code'] != 0){
                    continue;
                }

                //获取玩家个人数据
                $guildCompetitionMemberData = SzPersister::get()->getVo($uid, GameConst::ORM_NAME_UNION_COMPETITION_MEMBER);

                //刷新任务
                $guildCompetitionTask->setTaskId($randomTaskConf['randomTaskConf']['indexId']);
                $guildCompetitionTask->setNeedItem($randomTaskConf['needItem']);
                $guildCompetitionTask->setNeedProcess($randomTaskConf['needProcess']);
                $guildCompetitionTask->setTimeRange($randomTaskConf['timeRange']);
                $guildCompetitionTask->setProcess(0);
                $guildCompetitionTask->setUserId(0);
                $guildCompetitionTask->setState(0);
                $guildCompetitionTask->setHandleTime(0);
                $guildCompetitionTask->setUpdateTime($reqTime);

                $guildCompetitionTaskList->updateElement($taskData['pos'],$guildCompetitionTask);
                SzPersister::get()->setVoList($guildCompetitionTaskList);

                //设置玩家正在执行的任务
                $failNum = $guildCompetitionMemberData->getFailTaskNum();
                $guildCompetitionMemberData->setNowTask(0);
                $guildCompetitionMemberData->setFailTaskNum($failNum + 1);
                SzPersister::get()->setVo($guildCompetitionMemberData);

                //个人任务过期数据埋点
                StatisticsService::get()->saveLog($uid, GameConst::LOG_TYPE_USER_ORBIT, array(
                    'clientData' => array(
                        'tid' => 'Module:unionCompetition|action:expire|',
                        'item' => $taskData['taskId'].'&1',
                        'value' => 1
                    )
                ));
                //工会总数任务过期数据埋点
                StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $reqTime, array(
                    'clientData' => array(
                        'tid' => 'Module:unionCompetition|action:guildExpire|',
                        'item' => $guildId.'&'.$taskData['taskId'].'&1',
                        'value' => 1
                    )
                ));

                $taskConf = $randomTaskConf['randomTaskConf'];
                $temp = $guildCompetitionTask->toArray();
            }
            else{
                if ($guildCompetitionTask->getState() == 2 && $guildCompetitionTask->getCdTime() != 0 && $guildCompetitionTask->getCdTime() < $reqTime){
                    $guildCompetitionTask->setCdTime(0);
                    $guildCompetitionTask->setState(0);
                    $guildCompetitionTask->setUpdateTime($reqTime);
                    $guildCompetitionTaskList->updateElement($taskData['pos'],$guildCompetitionTask);
                    SzPersister::get()->setVoList($guildCompetitionTaskList);
                    $temp = $guildCompetitionTask->toArray();
                }
                else{
                    $temp = $taskData;
                }
            }

            $taskDatas[] = $this->taskFormatData($temp,$taskConf,$key);
        }

        $res['tasks'] = $taskDatas;
        return $res;
    }

    /**
     * 获取工会社团赛结算数据
     * @param $userId
     * @param $guildId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function getCompetitionHistory($userId,$guildId,$reqTime){
        $res = array(
            'code' => 0,
            'guild' => array(),
            'members' => array(),
            'failNum' => 0,
            'historyHighScore' => 0,
            'historyLv' => array(),
        );

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        //白名单允许进入
        if (!in_array($userId,GameConst::UNION_COMPETITION_USERID)){
            $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
            if ($isOpen != 1){
                $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//开关没有开启
                return $res;
            }
        }

        //获取玩家参与赛事公用配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['CONFIG_NOT_EXIST'];//配置不存在
            return $res;
        }

        //结算时刻请求返回
        $canRequest = $this->checkLastHour($groupConfig,$reqTime);
        if (!$canRequest){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//下一届未开启
            return $res;
        }

        //获取工会的公共数据
        /**
         * @var GuildCompetitionVo $guildCompetitionData
         */
        $guildCompetitionData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
        if (!$guildCompetitionData){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_95'];//社团赛事公共数据生成失败
            return $res;
        }
        //时间验证
        $startTime = $guildCompetitionData->getCreateTime();
        $endTime = $guildCompetitionData->getEndTime();
        if ($reqTime <= $startTime || $reqTime >= $endTime){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_98'];//不在社团竞赛循环时间内
            return $res;
        }
        $res['guild'] = $this->competitionFormatData($guildId,$guildCompetitionData);
        //获取参与玩家的社团赛数据
        $membersTaskData = array();
        $membersStr = json_decode($guildCompetitionData->getParticipant());
        if ($membersStr != '' || $membersStr != null){
            $totalTaskNum = $groupConfig['taskLimit'][$quality - 1];
            $members = explode(',',$membersStr);
            if (!empty($members)){
                foreach ($members as $key=>$memberId){
                    $membersTaskData[] = $this->getUserCompetitionData($memberId,$reqTime,$endTime,$totalTaskNum);
                }
            }
        }
        $res['members'] = $membersTaskData;

        //获取自己的个人数据
        /**
         * @var GuildCompetitionMemberVo $mineData
         */
        $mineData = SzPersister::get()->getVo($userId, GameConst::ORM_NAME_UNION_COMPETITION_MEMBER);
        if ($mineData){
            $res['failNum'] = $mineData->getFailTaskNum();
        }

        //获取社团的历史竞赛数据
        /**
         * @var GuildCompetitionHistoryVo $guildCompetitionHistory
         */
        $goldData = array();
        $silverData = array();
        $bronzeData = array();
        $guildCompetitionHistory = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_HISTORY);
        if ($guildCompetitionHistory){
            $res['historyHighScore'] = $guildCompetitionHistory->getHighest();
            $goldData = $this->competitionHistoryFormatData(GameConst::UNION_COMPETITION_GOLD,explode(',',json_decode($guildCompetitionHistory->getGold())));
            $silverData = $this->competitionHistoryFormatData(GameConst::UNION_COMPETITION_SILVER,explode(',',json_decode($guildCompetitionHistory->getSilver())));
            $bronzeData = $this->competitionHistoryFormatData(GameConst::UNION_COMPETITION_BRONZE,explode(',',json_decode($guildCompetitionHistory->getBronze())));
        }
        else{
            $goldData = $this->competitionHistoryFormatData(GameConst::UNION_COMPETITION_GOLD,explode(',',array()));
            $silverData = $this->competitionHistoryFormatData(GameConst::UNION_COMPETITION_SILVER,explode(',',array()));
            $bronzeData = $this->competitionHistoryFormatData(GameConst::UNION_COMPETITION_BRONZE,explode(',',array()));
        }
        $res['historyLv'] = array($goldData,$silverData,$bronzeData);

        return $res;
    }

    /**
     * 获取玩家社团赛个人数据
     * @param $userId
     * @param $reqTime
     * @param $endTime
     * @param $totalTaskNum
     * @return array
     * @throws SzException
     */
    public function getUserCompetitionData($userId,$reqTime,$endTime,$totalTaskNum)
    {
        $userData = array();
        $player = $userId;
        $score = 0;
        $claimTaskNum = 0;
        $succeedTaskNum = 0;
        $completeTaskNum = 0;
        /**
         * @var GuildCompetitionMemberVo $guildCompetitionMemberData
         */
        //获取玩家社团竞赛个人数据
        $guildCompetitionMemberData =  SzPersister::get()->getVo($userId, GameConst::ORM_NAME_UNION_COMPETITION_MEMBER);
        if ($guildCompetitionMemberData){
            $score = $guildCompetitionMemberData->getEpicyclePoint();
            $claimTaskNum = $guildCompetitionMemberData->getClaimTaskNum();
            $succeedTaskNum = $guildCompetitionMemberData->getFinishTaskNum();
            $completeTaskNum = $guildCompetitionMemberData->getFailTaskNum()+$guildCompetitionMemberData->getFinishTaskNum();
        }

        //数据格式化
        $userData['playerId'] = $player;
        $userData['score'] = $score;
        $userData['claimTaskNum'] = $claimTaskNum;
        $userData['succeedTaskNum'] = $succeedTaskNum;
        $userData['completeTaskNum'] = $completeTaskNum;

        return $userData;
    }

    /**
     * 接受任务
     * @param $userId
     * @param $guildId
     * @param $pos
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function receiveTask($userId,$guildId,$pos,$reqTime)
    {
        $res = array(
            'code' => 0,
            'task' => array(),
            'self' => array(),
            'items' => array()
        );

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        //白名单允许进入
        if (!in_array($userId,GameConst::UNION_COMPETITION_USERID)){
            $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
            if ($isOpen != 1){
                $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//开关没有开启
                return $res;
            }
        }

        $isNewGay = 0;
        $personNum = 0;
        //获取工会公用分组配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['CONFIG_NOT_EXIST'];//配置不存在
            return $res;
        }

        //结算时刻请求返回
        $canRequest = $this->checkLastHour($groupConfig,$reqTime);
        if (!$canRequest){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//下一届未开启
            return $res;
        }

        //获取工会的公共数据
        /**
         * @var GuildCompetitionVo $guildCompetitionData
         */
        $personNum = 0;
        $guildCompetitionData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
        if (!$guildCompetitionData){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_95'];//社团赛事公共数据生成失败
            return $res;
        }
        //时间验证
        $startTime = $guildCompetitionData->getCreateTime();
        $endTime = $guildCompetitionData->getEndTime();
        if ($reqTime <= $startTime || $reqTime >= $endTime){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_98'];//不在社团竞赛循环时间内
            return $res;
        }

        //验证玩家在本届公会赛中是否换其他工会
        $checkCode = $this->checkPlayer($userId,$guildId,$startTime,$endTime,$reqTime);
        if ($checkCode != 0){
            $res['code'] = $checkCode;
            return $res;
        }

        $quality = $guildCompetitionData->getQuality();
        //获取工会该任务数据
        /**
         * @var GuildCompetitionTaskVoList $guildCompetitionTaskList
         * @var GuildCompetitionTaskVo $guildCompetitionTask
         */
        $guildCompetitionTaskList = SzPersister::get()->getVoList($guildId, GameConst::ORM_NAME_UNION_COMPETITION_TASK);
        $guildCompetitionTask = $guildCompetitionTaskList->getElement($pos,false);
        if (!$guildCompetitionTask){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_96'];//社团赛事工会任务数据生成失败
            return $res;
        }

        $hasUserId = $guildCompetitionTask->getUserId();
        if ($hasUserId > 0){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_100'];
            return $res;
        }

        $taskIndexId = $guildCompetitionTask->getTaskId();
        $taskConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_TASKS, $taskIndexId, true);
        if (!$taskConf){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['CONFIG_NOT_EXIST'];//配置不存在
            return $res;
        }

        //验证任务是都可以接取
        $taskState = $guildCompetitionTask->getState();
        if ($taskState != 0){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_99'];//社团任务不可接取
            return $res;
        }
        /**
         * @var GuildCompetitionMemberVo $guildCompetitionMemberData
         */
        //获取玩家社团竞赛个人数据
        $guildCompetitionMemberData =  SzPersister::get()->getVo($userId, GameConst::ORM_NAME_UNION_COMPETITION_MEMBER);
        if (!$guildCompetitionMemberData){//没有任务创建任务
            $guildCompetitionMemberData = new GuildCompetitionMemberVo(
                $userId,
                0,
                0,
                $taskIndexId,
                1,
                0,
                0,
                $reqTime,
                $reqTime,
                $endTime,
                true
            );
        }
        else{//有任务的情况下，有且只有一个任务可以接受
            if ($guildCompetitionMemberData->getEndTime() < $reqTime){
                $guildCompetitionMemberData->setEpicyclePoint(0);
                $guildCompetitionMemberData->setEpicycleFlags(0);
                $guildCompetitionMemberData->setClaimTaskNum(1);
                $guildCompetitionMemberData->setFinishTaskNum(0);
                $guildCompetitionMemberData->setFailTaskNum(0);
                $guildCompetitionMemberData->setCreateTime($reqTime);
                $guildCompetitionMemberData->setUpdateTime($reqTime);
                $guildCompetitionMemberData->setEndTime($endTime);
            }
            else{
                if ($guildCompetitionMemberData->getNowTask()){
                    $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_105'];//社团赛事玩家已有任务在身
                    return $res;
                }
                //设置玩家正在执行的任务
                $guildCompetitionMemberData->setClaimTaskNum($guildCompetitionMemberData->getClaimTaskNum() + 1);
            }
            $guildCompetitionMemberData->setNowTask($taskIndexId);
        }

        //更新工会公共数据中的参与者名单
        $participant = json_decode($guildCompetitionData->getParticipant());
        if ($participant == '' || !$participant || empty($participant) || $participant == null){
            $guildCompetitionData->setParticipant($userId);
            $isNewGay = 1;
            $personNum = 1;
        }
        else{
            $participantArr = explode(',',$participant);
            if (!in_array($userId,$participantArr)){
                $participantArr[] = $userId;
                $guildCompetitionData->setParticipant(json_encode(implode(',',$participantArr)));
                $personNum = count($participantArr);
                $isNewGay = 1;
            }
        }

        //玩家接取任务
        $guildCompetitionTask->setUserId($userId);
        $guildCompetitionTask->setState(1);
        $guildCompetitionTask->setHandleTime($reqTime);
        $guildCompetitionTask->setUpdateTime($reqTime);
        $guildCompetitionTaskList->updateElement($pos,$guildCompetitionTask);

        SzPersister::get()->setVoList($guildCompetitionTaskList);
        SzPersister::get()->setVo($guildCompetitionMemberData);

        //更新积分保护基准值
        if ($isNewGay){
            //设置新加入的玩家头像框
            GameService::get()->handleEntity($userId, $groupConfig['pictureFrame'][$quality - 1], 1, true, true);
//            $newPointSpeed = $this->calculationBasisPoint($guildId,$groupConfig,$guildCompetitionData);
//            $guildCompetitionData->setPointSpeed($newPointSpeed);
            //获取玩家工会信息
            /**
             * @var GuildInfoVo $guildInfo
             */
            $guildInfo = SzPersister::get()->getVo(null, GameConst::ORM_NAME_GUILD_INFO, $guildId);
            $guildPersonNum = $guildInfo->getNum();
            //（公会参赛人数 * deduction2 / 公会总人数）^deduction1
            $deduction2 = explode(',',$groupConfig['deduction2'])[$quality - 1];
            $deduction1 = explode(',',$groupConfig['deduction1'])[$quality - 1];
            $newPointSpeed = ceil(pow((($personNum*$deduction2)/$guildPersonNum),$deduction1));
            $guildCompetitionData->setPointSpeed($newPointSpeed);

            $res['items'] = array($groupConfig['pictureFrame'][$quality - 1] => 1);

            //参赛人数上报
            StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $reqTime, array(
                'clientData' => array(
                    'tid' => 'Module:unionCompetition|action:getPersonNum|',
                    'item' => $guildId.'&personNum',
                    'value' => $personNum
                )
            ));
        }
        SzPersister::get()->setVo($guildCompetitionData);

        //获取玩家该赛季数据
        $competitionQuality = $guildCompetitionData->getQuality();
        //获取玩家个人数据
        $totalTaskNum = $groupConfig['taskLimit'][$competitionQuality - 1];
        $userData = $this->getUserCompetitionData($userId,$reqTime,$endTime,$totalTaskNum);

        //个人接受任务数据埋点
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:unionCompetition|action:receive|',
                'item' => $taskIndexId.'&1',
                'value' => 1
            )
        ));
        //工会总数接受任务数据埋点
        StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $reqTime, array(
            'clientData' => array(
                'tid' => 'Module:unionCompetition|action:guildReceive|',
                'item' => $guildId.'&'.$taskIndexId.'&1',
                'value' => 1
            )
        ));

        //任务数据格式化
        $res['task'] = $this->taskFormatData($guildCompetitionTask->toArray(),$taskConf);
        $res['self'] = $userData;
        return $res;
    }

    /**
     * 刷新任务
     * @param $userId
     * @param $guildId
     * @param $pos
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function updateTask($userId,$guildId,$pos,$reqTime)
    {
        $res = array(
            'code' => 0,
            'task' => array(),
            'self' =>array()
        );

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        //白名单允许进入
        if (!in_array($userId,GameConst::UNION_COMPETITION_USERID)){
            $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
            if ($isOpen != 1){
                $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//开关没有开启
                return $res;
            }
        }

        //获取工会公用分组配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['CONFIG_NOT_EXIST'];//配置不存在
            return $res;
        }

        //结算时刻请求返回
        $canRequest = $this->checkLastHour($groupConfig,$reqTime);
        if (!$canRequest){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//下一届未开启
            return $res;
        }

        //获取工会的公共数据
        /**
         * @var GuildCompetitionVo $guildCompetitionData
         */
        $guildCompetitionData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
        if (!$guildCompetitionData){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_95'];//社团赛事公共数据生成失败
            return $res;
        }
        //时间验证
        $startTime = $guildCompetitionData->getCreateTime();
        $endTime = $guildCompetitionData->getEndTime();
        if ($reqTime <= $startTime || $reqTime >= $endTime){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_98'];//不在社团竞赛循环时间内
            return $res;
        }

        //验证玩家在本届公会赛中是否换其他工会
        $checkCode = $this->checkPlayer($userId,$guildId,$startTime,$endTime,$reqTime);
        if ($checkCode != 0){
            $res['code'] = $checkCode;
            return $res;
        }

        //获取工会该任务数据
        /**
         * @var GuildCompetitionTaskVoList $guildCompetitionTaskList
         * @var GuildCompetitionTaskVo $guildCompetitionTask
         */
        $guildCompetitionTaskList = SzPersister::get()->getVoList($guildId, GameConst::ORM_NAME_UNION_COMPETITION_TASK);
        $guildCompetitionTask = $guildCompetitionTaskList->getElement($pos,false);
        if (!$guildCompetitionTask){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_96'];//社团赛事工会任务数据生成失败
            return $res;
        }
        $taskState = $guildCompetitionTask->getState();
        if ($taskState == 2){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_102'];//社团任务cd中
            return $res;
        }

        //有且只有一个任务可以接受
        /**
         * @var GuildCompetitionMemberVo $guildCompetitionMemberData
         */
        //获取玩家社团竞赛个人数据
        $guildCompetitionMemberData =  SzPersister::get()->getVo($userId, GameConst::ORM_NAME_UNION_COMPETITION_MEMBER);
        if (!$guildCompetitionMemberData){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_97'];//社团赛事个人数据出错
            return $res;
        }

        //验证任务是都可以接取
        $oldTaskIndexId = $guildCompetitionTask->getTaskId();
        $taskExecutor = $guildCompetitionTask->getUserId();
        if ($taskExecutor != $userId){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_100'];//社团任务已经接取
            return $res;
        }
        if ($oldTaskIndexId != $guildCompetitionMemberData->getNowTask()){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_106'];//社团任务不一致
            return $res;
        }

        //获取玩家所属工会的赛事品质
        $quality = $guildCompetitionData->getQuality();
        $randomTaskConf = $this->getRandomTaskConf($quality);
        if ($randomTaskConf['code'] != 0){
            $res['code'] = $randomTaskConf['code'];
            return $res;
        }

        //消耗道具
        $useItem = $groupConfig['taskRefresh'];
        foreach ($useItem as $itemId=>$useNum){
            GameService::get()->handleEntity($userId,$itemId, $useNum, true);
        }

        //玩家刷新任务
        $guildCompetitionTask->setTaskId($randomTaskConf['randomTaskConf']['indexId']);
        $guildCompetitionTask->setNeedItem($randomTaskConf['needItem']);
        $guildCompetitionTask->setNeedProcess($randomTaskConf['needProcess']);
        $guildCompetitionTask->setProcess(0);
        $guildCompetitionTask->setTimeRange($randomTaskConf['timeRange']);
        $guildCompetitionTask->setState(1);
        $guildCompetitionTask->setHandleTime($reqTime);
        $guildCompetitionTask->setUpdateTime($reqTime);

        $guildCompetitionTaskList->updateElement($pos,$guildCompetitionTask);
        SzPersister::get()->setVoList($guildCompetitionTaskList);

        //设置玩家正在执行的任务
        $guildCompetitionMemberData->setNowTask($randomTaskConf['randomTaskConf']['indexId']);
        SzPersister::get()->setVo($guildCompetitionMemberData);

        //获取玩家该赛季数据
        $competitionQuality = $guildCompetitionData->getQuality();
        //获取玩家个人数据
        $totalTaskNum = $groupConfig['taskLimit'][$competitionQuality - 1];
        $userData = $this->getUserCompetitionData($userId,$reqTime,$endTime,$totalTaskNum);

        //个人刷新任务数据埋点
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:unionCompetition|action:update|',
                'item' => $oldTaskIndexId.'&1',
                'value' => 1
            )
        ));
        //工会总数更新任务数据埋点
        StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $reqTime, array(
            'clientData' => array(
                'tid' => 'Module:unionCompetition|action:guildUpdate|',
                'item' => $guildId.'&'.$oldTaskIndexId.'&1',
                'value' => 1
            )
        ));

        //任务数据格式化
        $res['task'] = $this->taskFormatData($guildCompetitionTask->toArray(),$randomTaskConf['randomTaskConf']);
        $res['self'] = $userData;
        return $res;
    }

    /**
     * 提交任务
     * @param $userId
     * @param $guildId
     * @param $pos
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function submitTask($userId,$guildId,$pos,$reqTime)
    {
        $res = array(
            'code' => 0,
            'task' => array(),
            'self' => array(),
            'items' => array(),
//            'guild' => array(),
            'guildScore' => 0,
            'itemsGuild' => array(),
        );

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        //白名单允许进入
        if (!in_array($userId,GameConst::UNION_COMPETITION_USERID)){
            $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
            if ($isOpen != 1){
                $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//开关没有开启
                return $res;
            }
        }

        //获取工会公用分组配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['CONFIG_NOT_EXIST'];//配置不存在
            return $res;
        }

        //结算时刻请求返回
        $canRequest = $this->checkLastHour($groupConfig,$reqTime);
        if (!$canRequest){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//下一届未开启
            return $res;
        }

        //获取工会的公共数据
        /**
         * @var GuildCompetitionVo $guildCompetitionData
         */
        $guildCompetitionData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
        if (!$guildCompetitionData){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_95'];//社团赛事公共数据生成失败
            return $res;
        }
        //时间验证
        $startTime = $guildCompetitionData->getCreateTime();
        $endTime = $guildCompetitionData->getEndTime();
        if ($reqTime <= $startTime || $reqTime >= $endTime){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_98'];//不在社团竞赛循环时间内
            return $res;
        }

        //验证玩家在本届公会赛中是否换其他工会
        $checkCode = $this->checkPlayer($userId,$guildId,$startTime,$endTime,$reqTime);
        if ($checkCode != 0){
            $res['code'] = $checkCode;
            return $res;
        }

        //获取工会该任务数据
        /**
         * @var GuildCompetitionTaskVoList $guildCompetitionTaskList
         * @var GuildCompetitionTaskVo $guildCompetitionTask
         */
        $guildCompetitionTaskList = SzPersister::get()->getVoList($guildId, GameConst::ORM_NAME_UNION_COMPETITION_TASK);
        $guildCompetitionTask = $guildCompetitionTaskList->getElement($pos,false);
        if (!$guildCompetitionTask){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_96'];//社团赛事工会任务数据生成失败
            return $res;
        }

        /**
         * @var GuildCompetitionMemberVo $guildCompetitionMemberData
         */
        //获取玩家社团竞赛个人数据
        $guildCompetitionMemberData =  SzPersister::get()->getVo($userId, GameConst::ORM_NAME_UNION_COMPETITION_MEMBER);
        if (!$guildCompetitionMemberData){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_104'];//社团赛事个人数据出错
            return $res;
        }

        //验证任务是都可以接取
        $submitTaskIndexId = $guildCompetitionTask->getTaskId();
        if ($submitTaskIndexId != $guildCompetitionMemberData->getNowTask()){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_106'];//社团任务不一致
            return $res;
        }

        $taskExecutor = $guildCompetitionTask->getUserId();
        if ($taskExecutor != $userId){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_101'];//社团任务已经接取
            return $res;
        }

        $taskState = $guildCompetitionTask->getState();
        if ($taskState != 1){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_102'];//社团任务cd中
            return $res;
        }

        $endCommitTime = $guildCompetitionTask->getHandleTime() + $guildCompetitionTask->getTimeRange();
        if ($reqTime > $endCommitTime){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_110'];//社团任务超时提交，
            return $res;
        }

        $nowProcess = $guildCompetitionTask->getProcess();
        if ($nowProcess != $guildCompetitionTask->getNeedProcess()){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_107'];//社团任务未完成
            return $res;
        }

        //*********给玩家个人数据更新
        $oldTaskConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_TASKS, $guildCompetitionTask->getTaskId(), true);
        //本次社团赛事个人数据加分
        $oldPoint = $guildCompetitionMemberData->getEpicyclePoint();
        $pointNum = $guildCompetitionTask->getNeedProcess();
        $getPoint = ceil($pointNum*$oldTaskConf['score']);

        //*********获取玩家所属工会的赛事品质
        $quality = $guildCompetitionData->getQuality();
        //获取该品质赛事可获得的旗帜数量
        $limitFlagNum = $groupConfig['flagNum'][$quality - 1];
        //工会积分获取
        $guildScore = $guildCompetitionData->getPoint();
        $totalScore = $guildScore + $getPoint;
        //工会旗帜获取
        $guildFlags = $guildCompetitionData->getFlags();
        $totalFlags = $guildFlags + 1;
        //下一段赛程
        $nextStep = $guildCompetitionData->getStep() + 1;
        $needScore = $groupConfig['flagdistance'][$quality - 1]*$nextStep;

        //本次社团赛事个人任务次数更新
        $olsTaskFinish = $guildCompetitionMemberData->getFinishTaskNum();
        $guildCompetitionMemberData->setEpicyclePoint($oldPoint + $getPoint);
        $guildCompetitionMemberData->setNowTask(0);
        $guildCompetitionMemberData->setFinishTaskNum($olsTaskFinish + 1);
        $guildCompetitionMemberData->setUpdateTime($reqTime);
        //验证工会本届积分是否满足发送旗帜
        if ($totalScore >= $needScore && $nextStep <= $limitFlagNum){
            $guildCompetitionMemberData->setEpicycleFlags($guildCompetitionMemberData->getEpicycleFlags() + 1);
        }
        SzPersister::get()->setVo($guildCompetitionMemberData);

        //发放马蹄铁
        GameService::get()->handleEntity($userId,GameConst::UNION_COMPETITION_GET_HORSE_SHOE, $getPoint,  true);
        CommonFunctionService::get()->reportResourceUseDetails(GameConst::FUNC_UNION_COMPETITION,$userId,1,GameConst::UNION_COMPETITION_GET_HORSE_SHOE.':'.$getPoint.'|','submitTask');//获得资源上报
        $res['items'][GameConst::UNION_COMPETITION_GET_HORSE_SHOE] = $getPoint;
        /**
         * 获取玩家商品数据
         * @var ModuleItemVoList $itemList
         */
        $itemList = SzPersister::get()->getVoList($userId, ModuleItemConst::ORM_NAME_ITEM);
        $horseItem = $itemList->getElementsByItemDefId(GameConst::UNION_COMPETITION_HORSE_SHOE);
        if (!$horseItem) {
            $horseNum = 0;
        }
        else{
            // 获取道具的拥有数量
            $horseNum = $itemList->getItemDefCount(GameConst::UNION_COMPETITION_HORSE_SHOE);
        }
        //个人马蹄铁总数埋点
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => GameConst::UNION_COMPETITION_GET_HORSE_SHOE.':'.$horseNum.'|',
                'item' => 'point',
                'value' => 1
            )
        ));

        //验证工会本届积分是否满足发送旗帜
        if ($totalScore >= $needScore && $nextStep <= $limitFlagNum){
            $guildCompetitionData->setStep($nextStep);
            $guildCompetitionData->setFlags($totalFlags);

            //获取工会所有参赛人员
            $guildMembers = explode(',',json_decode($guildCompetitionData->getParticipant()));
            $res['itemsGuild'] = array(GameConst::UNION_COMPETITION_GET_FLAG => 1);
            //发放旗帜给每个社员
            foreach ($guildMembers as $uid){
                GameService::get()->handleEntity($uid,GameConst::UNION_COMPETITION_GET_FLAG, 1,  true);
                CommonFunctionService::get()->reportResourceUseDetails(GameConst::FUNC_UNION_COMPETITION,$uid,1,GameConst::UNION_COMPETITION_GET_FLAG.':1|','submitTask');//获得资源上报
                $flagItem = $itemList->getElementsByItemDefId(GameConst::UNION_COMPETITION_FLAG);
                if (!$flagItem) {
                    $flagNum = 0;
                }
                else{
                    // 获取道具的拥有数量
                    $flagNum = $itemList->getItemDefCount(GameConst::UNION_COMPETITION_FLAG);
                }
                //个人旗帜总数埋点
                StatisticsService::get()->saveLog($uid, GameConst::LOG_TYPE_USER_ORBIT, array(
                    'clientData' => array(
                        'tid' => GameConst::UNION_COMPETITION_GET_FLAG.':'.$flagNum.'|',
                        'item' => 'flag',
                        'value' => 1
                    )
                ));

                /**
                 * @var GuildCompetitionMemberVo $guildCompetitionOthersData
                 */
                //获取玩家社团竞赛个人数据
                $guildCompetitionOthersData =  SzPersister::get()->getVo($uid, GameConst::ORM_NAME_UNION_COMPETITION_MEMBER);
                if ($guildCompetitionOthersData && $uid != $userId){
                    $guildCompetitionOthersData->setEpicycleFlags($guildCompetitionOthersData->getEpicycleFlags() + 1);
                    $guildCompetitionOthersData->setUpdateTime($reqTime);
                    SzPersister::get()->setVo($guildCompetitionOthersData);
                }
            }
            //工会旗帜总数埋点
            StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $reqTime, array(
                'clientData' => array(
                    'tid' => 'Module:unionCompetition|action:guildFlag|',
                    'item' => $guildId.'&flagNum',
                    'value' => $totalFlags
                )
            ));
        }

        $guildCompetitionData->setPoint($totalScore);
        $guildCompetitionData->setUpdateTime($reqTime);
        SzPersister::get()->setVo($guildCompetitionData);

        //工会积分总数埋点
        StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $reqTime, array(
            'clientData' => array(
                'tid' => 'Module:unionCompetition|action:guildPoint|',
                'item' => $guildId.'&pointNum',
                'value' => $totalScore
            )
        ));

        //获取随机任务配置
        $randomTaskConf = $this->getRandomTaskConf($quality);
        if ($randomTaskConf['code'] != 0){
            $res['code'] = $randomTaskConf['code'];
            return $res;
        }

        //玩家刷新任务
        $guildCompetitionTask->setUserId(0);
        $guildCompetitionTask->setTaskId($randomTaskConf['randomTaskConf']['indexId']);
        $guildCompetitionTask->setNeedItem($randomTaskConf['needItem']);
        $guildCompetitionTask->setNeedProcess($randomTaskConf['needProcess']);
        $guildCompetitionTask->setProcess(0);
        $guildCompetitionTask->setTimeRange($randomTaskConf['timeRange']);
        $guildCompetitionTask->setState(0);
        $guildCompetitionTask->setHandleTime(0);
        $guildCompetitionTask->setUpdateTime($reqTime);

        $guildCompetitionTaskList->updateElement($pos,$guildCompetitionTask);
        SzPersister::get()->setVoList($guildCompetitionTaskList);

        //获取玩家该赛季数据
        $competitionQuality = $guildCompetitionData->getQuality();
        //获取玩家个人数据
        $totalTaskNum = $groupConfig['taskLimit'][$competitionQuality - 1];
        $userData = $this->getUserCompetitionData($userId,$reqTime,$endTime,$totalTaskNum);

        //提交任务数据埋点
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:unionCompetition|action:submit|',
                'item' => $submitTaskIndexId.'&1',
                'value' => 1
            )
        ));

        //工会总数提交任务数据埋点
        StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $reqTime, array(
            'clientData' => array(
                'tid' => 'Module:unionCompetition|action:guildSubmit|',
                'item' => $guildId.'&'.$submitTaskIndexId.'&1',
                'value' => 1
            )
        ));

        //任务数据格式化
        $res['self'] = $userData;
        $res['task'] = $this->taskFormatData($guildCompetitionTask->toArray(),$randomTaskConf['randomTaskConf']);
        $res['guildScore'] = $guildCompetitionData->getPoint();
//        $res['guild'] = $this->competitionFormatData($guildId,$guildCompetitionData);
        return $res;
    }

    /**
     * 删除任务
     * @param $userId
     * @param $guildId
     * @param $pos
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function deleteTask($userId,$guildId,$pos,$reqTime)
    {
        $res = array(
            'code' => 0,
            'task' => array()
        );

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        //白名单允许进入
        if (!in_array($userId,GameConst::UNION_COMPETITION_USERID)){
            $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
            if ($isOpen != 1){
                $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//开关没有开启
                return $res;
            }
        }

        //获取玩家参与赛事公用配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['CONFIG_NOT_EXIST'];//配置不存在
            return $res;
        }

        //结算时刻请求返回
        $canRequest = $this->checkLastHour($groupConfig,$reqTime);
        if (!$canRequest){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//下一届未开启
            return $res;
        }

        //获取工会的公共数据
        /**
         * @var GuildCompetitionVo $guildCompetitionData
         */
        $guildCompetitionData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
        if (!$guildCompetitionData){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_95'];//社团赛事公共数据生成失败
            return $res;
        }
        //时间验证
        $startTime = $guildCompetitionData->getCreateTime();
        $endTime = $guildCompetitionData->getEndTime();

        if ($reqTime <= $startTime || $reqTime >= $endTime){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_98'];//不在社团竞赛循环时间内
            return $res;
        }

        //验证玩家身份
        /**
         * @var $guildMemberInfoList GuildMemberInfoVoList
         * @var $userMemberInfo GuildMemberInfoVo
         */
        $guildMemberInfoList = SzPersister::get()->getVoList($guildId, GameConst::ORM_NAME_GUILD_MEMBER_INFO);
        $userMemberInfo = $guildMemberInfoList->getElement($userId,false);
        if ($userMemberInfo->getPosition() > 2) {
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_108'];//社团任务删除权限不够
            return $res;
        }

        //获取工会该任务数据
        /**
         * @var GuildCompetitionTaskVoList $guildCompetitionTaskList
         * @var GuildCompetitionTaskVo $guildCompetitionTask
         */
        $guildCompetitionTaskList = SzPersister::get()->getVoList($guildId, GameConst::ORM_NAME_UNION_COMPETITION_TASK);
        $guildCompetitionTask = $guildCompetitionTaskList->getElement($pos,false);
        if (!$guildCompetitionTask){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_96'];//社团赛事工会任务数据生成失败
            return $res;
        }

        //验证任务是否可以删除
        $taskExecutor = $guildCompetitionTask->getUserId();
        if ($taskExecutor != 0){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_100'];//社团任务已经接取
            return $res;
        }

        $taskState = $guildCompetitionTask->getState();
        if ($taskState == 2){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_102'];//社团任务cd中
            return $res;
        }
        $delTaskIndexId = $guildCompetitionTask->getTaskId();

        //更新积分保护基准值
//        $newPointSpeed = $this->calculationBasisPoint($guildId,$groupConfig,$guildCompetitionData);
        //记录工会删除数据
        $guildCompetitionData->setDelTask($guildCompetitionData->getDelTask() + 1);
        $guildCompetitionData->setUpdateTime($reqTime);
//        $guildCompetitionData->setPointSpeed($newPointSpeed);
        SzPersister::get()->setVo($guildCompetitionData);

        //获取玩家所属工会的赛事品质
        $quality = $guildCompetitionData->getQuality();
        $randomTaskConf = $this->getRandomTaskConf($quality);
        if ($randomTaskConf['code'] != 0){
            $res['code'] = $randomTaskConf['code'];
            return $res;
        }

        //刷新工会任务
        $guildCompetitionTask->setUserId(0);
        $guildCompetitionTask->setTaskId($randomTaskConf['randomTaskConf']['indexId']);
        $guildCompetitionTask->setNeedItem($randomTaskConf['needItem']);
        $guildCompetitionTask->setNeedProcess($randomTaskConf['needProcess']);
        $guildCompetitionTask->setProcess(0);
        $guildCompetitionTask->setTimeRange($randomTaskConf['timeRange']);
        $guildCompetitionTask->setState(2);
        $guildCompetitionTask->setCdTime($reqTime + $groupConfig['countDown']);
        $guildCompetitionTask->setHandleTime(0);
        $guildCompetitionTask->setUpdateTime($reqTime);
        $guildCompetitionTaskList->updateElement($pos,$guildCompetitionTask);
        SzPersister::get()->setVoList($guildCompetitionTaskList);

        //提交任务数据埋点
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:unionCompetition|action:delete|',
                'item' => $delTaskIndexId.'&1',
                'value' => 1
            )
        ));
        //工会总数删除任务数据埋点
        StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $reqTime, array(
            'clientData' => array(
                'tid' => 'Module:unionCompetition|action:guildDelete|',
                'item' => $guildId.'&'.$delTaskIndexId.'&1',
                'value' => 1
            )
        ));

        //任务数据格式化
        $res['task'] = $this->taskFormatData($guildCompetitionTask->toArray(),$randomTaskConf['randomTaskConf']);
        return $res;
    }

    /**
     * 过期导致任务刷新
     * @param $userId
     * @param $guildId
     * @param $pos
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function overdueUpdateTask($userId,$guildId,$pos,$reqTime){
        $res = array(
            'code' => 0,
            'task' => array(),
            'self' => array()
        );

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
        if ($isOpen != 1){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//开关没有开启
            return $res;
        }

        //获取工会公用分组配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['CONFIG_NOT_EXIST'];//配置不存在
            return $res;
        }

        //结算时刻请求返回
        $canRequest = $this->checkLastHour($groupConfig,$reqTime);
        if (!$canRequest){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//下一届未开启
            return $res;
        }

        //获取工会的公共数据
        /**
         * @var GuildCompetitionVo $guildCompetitionData
         */
        $guildCompetitionData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
        if (!$guildCompetitionData){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_95'];//社团赛事公共数据生成失败
            return $res;
        }
        //时间验证
        $startTime = $guildCompetitionData->getCreateTime();
        $endTime = $guildCompetitionData->getEndTime();
        if ($reqTime <= $startTime || $reqTime >= $endTime){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_98'];//不在社团竞赛循环时间内
            return $res;
        }

        //获取工会该任务数据
        /**
         * @var GuildCompetitionTaskVoList $guildCompetitionTaskList
         * @var GuildCompetitionTaskVo $guildCompetitionTask
         */
        $guildCompetitionTaskList = SzPersister::get()->getVoList($guildId, GameConst::ORM_NAME_UNION_COMPETITION_TASK);
        $guildCompetitionTask = $guildCompetitionTaskList->getElement($pos,false);
        if (!$guildCompetitionTask){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_96'];//社团赛事工会任务数据生成失败
            return $res;
        }
        $taskState = $guildCompetitionTask->getState();
        if ($taskState == 2){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_102'];//社团任务cd中
            return $res;
        }

        //有且只有一个任务可以接受
        /**
         * @var GuildCompetitionMemberVo $guildCompetitionMemberData
         */
        //获取玩家社团竞赛个人数据
        $guildCompetitionMemberData =  SzPersister::get()->getVo($userId, GameConst::ORM_NAME_UNION_COMPETITION_MEMBER);
        if (!$guildCompetitionMemberData){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_97'];//社团赛事个人数据出错
            return $res;
        }

        //验证任务是都可以接取
        $taskExecutor = $guildCompetitionTask->getUserId();
        if ($taskExecutor != $userId){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_101'];//社团任务已经接取
            return $res;
        }
        $expireTaskIndexId = $guildCompetitionTask->getTaskId();
        if ($expireTaskIndexId != $guildCompetitionMemberData->getNowTask()){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_106'];//社团任务不一致
            return $res;
        }

        //获取玩家所属工会的赛事品质
        $quality = $guildCompetitionData->getQuality();
        $randomTaskConf = $this->getRandomTaskConf($quality);
        if ($randomTaskConf['code'] != 0){
            $res['code'] = $randomTaskConf['code'];
            return $res;
        }

        //刷新任务
        $guildCompetitionTask->setTaskId($randomTaskConf['randomTaskConf']['indexId']);
        $guildCompetitionTask->setNeedItem($randomTaskConf['needItem']);
        $guildCompetitionTask->setNeedProcess($randomTaskConf['needProcess']);
        $guildCompetitionTask->setTimeRange($randomTaskConf['timeRange']);
        $guildCompetitionTask->setProcess(0);
        $guildCompetitionTask->setUserId(0);
        $guildCompetitionTask->setState(0);
        $guildCompetitionTask->setHandleTime(0);
        $guildCompetitionTask->setUpdateTime($reqTime);

        $guildCompetitionTaskList->updateElement($pos,$guildCompetitionTask);
        SzPersister::get()->setVoList($guildCompetitionTaskList);

        //设置玩家正在执行的任务
        $failNum = $guildCompetitionMemberData->getFailTaskNum();
        $guildCompetitionMemberData->setNowTask(0);
        $guildCompetitionMemberData->setFailTaskNum($failNum + 1);
        SzPersister::get()->setVo($guildCompetitionMemberData);

        //获取玩家该赛季数据
        $competitionQuality = $guildCompetitionData->getQuality();
        //获取玩家个人数据
        $totalTaskNum = $groupConfig['taskLimit'][$competitionQuality - 1];
        $userData = $this->getUserCompetitionData($userId,$reqTime,$endTime,$totalTaskNum);

        //个人任务过期数据埋点
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:unionCompetition|action:expire|',
                'item' => $expireTaskIndexId.'&1',
                'value' => 1
            )
        ));
        //工会总数任务过期数据埋点
        StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $reqTime, array(
            'clientData' => array(
                'tid' => 'Module:unionCompetition|action:guildExpire|',
                'item' => $guildId.'&'.$expireTaskIndexId.'&1',
                'value' => 1
            )
        ));

        //任务数据格式化
        $res['self'] = $userData;
        $res['task'] = $this->taskFormatData($guildCompetitionTask->toArray(),$randomTaskConf['randomTaskConf']);
        return $res;
    }

    /**
     * 获取随机刷新的任务配置
     * @param $quality
     * @return array
     */
    public function getRandomTaskConf($quality)
    {
        $res = array(
            'code' => 0,
            'randomTaskConf' => array(),
            'needItem' => 0,
            'needProcess' => 0,
            'timeRange' => 0,
        );
        //进行任务随机刷新
        $taskShowWeightArr = array();
        $qualityTaskConf = array();
        //获取任务配置表
        $configs = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_TASKS, null, true);
        foreach ($configs as $key=>$conf){
            if ($conf['leagueMatch'] == $quality){
                $qualityTaskConf[$conf['indexId']] = $conf;
                $taskShowWeightArr[] = array('tid'=>$conf['indexId'],'weight'=>$conf['weights']);
            }
        }
        $newIndexId = $this->randomTaskIdByWeight($taskShowWeightArr)['tid'];
        $randomTaskConf = $qualityTaskConf[$newIndexId];
        if (empty($qualityTaskConf) || empty($taskShowWeightArr) || empty($randomTaskConf)){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_103'];//社团任务随机失败
            return $res;
        }
        $res['randomTaskConf'] = $randomTaskConf;

        $needItem = 0;
        if ($randomTaskConf['taskitems'] != '0'){
            $items = explode(';',$randomTaskConf['taskitems']);
            $needItem = $items[array_rand($items)];
        }
        if ($needItem != 0){
            $res['needItem'] = $needItem;
        }

        $needProcess = rand($randomTaskConf['randomNum'][0],$randomTaskConf['randomNum'][1]);
        $timeRange = $needProcess*$randomTaskConf['limitedTime'];

        $res['needProcess'] = $needProcess;
        $res['timeRange'] = $timeRange;

        return $res;
    }

    /**
     * 获取小组赛数据
     * @param $guildId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function getCompetitionGroupInfo($guildId,$reqTime)
    {
        $res = array(
            'code' => 0,
            'guilds' => array(),
            'scoreAdd' => 0
        );

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        //白名单允许进入
        if (!in_array($guildId,GameConst::UNION_COMPETITION_GUILDID)){
            $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
            if ($isOpen != 1){
                $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//开关没有开启
                return $res;
            }
        }

        $guildDatas = array();
        //获取玩家参与赛事公用配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['CONFIG_NOT_EXIST'];//配置不存在
            return $res;
        }

        //结算时刻请求返回
        $canRequest = $this->checkLastHour($groupConfig,$reqTime);
        if (!$canRequest){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//下一届未开启
            return $res;
        }

        //获取工会的公共数据
        /**
         * @var GuildCompetitionVo $guildCompetitionData
         */
        $guildCompetitionData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
        if (!$guildCompetitionData){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_95'];//社团赛事公共数据生成失败
            return $res;
        }
        //时间验证
        $startTime = $guildCompetitionData->getCreateTime();
        $endTime = $guildCompetitionData->getEndTime();
        if ($reqTime <= $startTime || $reqTime >= $endTime){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_98'];//不在社团竞赛循环时间内
            return $res;
        }

        //获取工会的品质以及小组
        $quality = $guildCompetitionData->getQuality();
        $groupId = $guildCompetitionData->getGroupId();

        //获得小组赛分组数据
        /**
         * @var GuildCompetitionLibraryVo $guildGroupByQualityData
         */
        $guildGroupByQualityData = SzPersister::get()->getVo($quality, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);
        if (!$guildGroupByQualityData){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_111'];//社团赛事分组数据错误
            return $res;
        }

        $guildsArr = array();
        $groupDataStr = explode(';',$guildGroupByQualityData->getGuildsByGroup());
        foreach ($groupDataStr as $key=>$data){
            if (explode(':',$data)[0] == $groupId){
                $guildsArr = explode(',',(explode(':',$data)[1]));
            }
        }

        /**
         * @var GuildCompetitionLibraryVo $otherGuildCompetitionData
         */
        foreach ($guildsArr as $key=>$gid){
            $otherGuildCompetitionData = SzPersister::get()->getVo($gid, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
            if ($otherGuildCompetitionData){
                $guildDatas[] = $this->competitionFormatData($gid,$otherGuildCompetitionData);
            }
        }

        //工会自己的保护分数
        $res['scoreAdd'] = $guildCompetitionData->getPointSpeed();
        $res['guilds'] = $guildDatas;
        return $res;
    }

    /**
     * 换宝箱奖励
     * @param $userId
     * @param $guildId
     * @param $giftIndexId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function getTreasureChest($userId,$guildId,$giftIndexId,$reqTime)
    {
        $res = array(
            'code' => 0,
            'state' => 0,
            'items' => array()
        );

        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        //白名单允许进入
        if (!in_array($userId,GameConst::UNION_COMPETITION_USERID)){
            //验证社团竞赛系统是否开启
            $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
            if ($isOpen != 1){
                $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//开关没有开启
                return $res;
            }
        }

        //获取玩家参与赛事公用配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['CONFIG_NOT_EXIST'];//配置不存在
            return $res;
        }

        //结算时刻请求返回
        $canRequest = $this->checkLastHour($groupConfig,$reqTime);
        if (!$canRequest){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//下一届未开启
            return $res;
        }

        //获取宝箱配置
        $giftConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_GIFT, $giftIndexId, true);
        if (!$giftConf || empty($giftConf)){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['CONFIG_NOT_EXIST'];//配置不存在
            return $res;
        }

        //获取各个时间段
        $rStartTime = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_START_TIME);
        if ($rStartTime == 0 || $rStartTime == null || $rStartTime == ''){
            $rStartTime = 0;
        }
        $rSettlementTime = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SETTLEMENT_TIME);
        if ($rSettlementTime == 0 || $rSettlementTime == null || $rSettlementTime == ''){
            $rSettlementTime = 0;
        }

        if ($reqTime < $rStartTime || $reqTime > $rSettlementTime){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_116'];
            return $res;
        }
        //获取玩家当前所属的赛事品质
        /**
         * @var GuildCompetitionVo $guildCompetitionData
         */
        $guildCompetitionData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
        if (!$guildCompetitionData){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_95'];//数据不存在
            return $res;
        }

        $quality = $guildCompetitionData->getQuality();
        if (in_array($giftIndexId,$groupConfig['horseshoeBox'])){
            if ($groupConfig['horseshoeBox'][$quality - 1] != $giftIndexId){
                $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_117'];
                return $res;
            }
        }

        /**
         * 获取玩家商品数据
         * @var ModuleItemVoList $itemList
         */
        $itemList = SzPersister::get()->getVoList($userId, ModuleItemConst::ORM_NAME_ITEM);
        //获取消耗道具
        foreach ($giftConf['payOut'] as $itemId=>$num){
            //玩家消耗
            GameService::get()->handleEntity($userId, $itemId, $num,  true);
            if ($itemId == GameConst::UNION_COMPETITION_CONSUME_FLAG){
                $flagItem = $itemList->getElementsByItemDefId(GameConst::UNION_COMPETITION_FLAG);
                if (!$flagItem) {
                    $flagNum = 0;
                }
                else{
                    // 获取道具的拥有数量
                    $flagNum = $itemList->getItemDefCount(GameConst::UNION_COMPETITION_FLAG);
                }
                //个人旗帜总数埋点
                StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
                    'clientData' => array(
                        'tid' => GameConst::UNION_COMPETITION_CONSUME_FLAG.':'.$flagNum.'|',
                        'item' => 'flag',
                        'value' => 1
                    )
                ));
            }
            if ($itemId == GameConst::UNION_COMPETITION_CONSUME_HORSE_SHOE){
                $horseItem = $itemList->getElementsByItemDefId(GameConst::UNION_COMPETITION_HORSE_SHOE);
                if (!$horseItem) {
                    $horseNum = 0;
                }
                else{
                    // 获取道具的拥有数量
                    $horseNum = $itemList->getItemDefCount(GameConst::UNION_COMPETITION_HORSE_SHOE);
                }
                //个人马蹄铁总数埋点
                StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
                    'clientData' => array(
                        'tid' => GameConst::UNION_COMPETITION_CONSUME_HORSE_SHOE.':'.$horseNum.'|',
                        'item' => 'point',
                        'value' => 1
                    )
                ));
            }
        }

        //获得权重奖励
        $getReward = $this->getRewardArr($giftConf);
        //获得固定奖励
        foreach ($giftConf['mustDropItems'] as $itemKey=>$mustNum){
            if (isset($getReward[$itemKey])){
                $getReward[$itemKey] += $mustNum;
            }
            else{
                $getReward[$itemKey] = $mustNum;
            }
        }

        //发放道具
        $input = '';
        foreach ($getReward as $itemId1=>$num1){
            GameService::get()->handleEntity($userId, $itemId1, $num1,  true);
            $input .= $itemId1.':'.$num1.'|';
        }

        //兑换宝箱数据埋点
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_OUTPUT, array(
            'clientData' => array(
                'tid' => $input,
                'item' => $giftIndexId,
                'value' => 1
            )
        ));

        $res['items'] = $getReward;
        $res['state'] = 1;
        return $res;
    }

    /**
     * 计算小时基准加分
     * @param $guildId
     * @param $groupConfig
     * @param $guildCompetitionData
     * @return float|int
     * @throws SzException
     */
    public function calculationBasisPoint($guildId,$groupConfig,$guildCompetitionData)
    {
        $newPointSpeed = 0;
        //获取玩家工会信息
        /**
         * @var GuildInfoVo $guildInfo
         */
        $guildInfo = SzPersister::get()->getVo(null, GameConst::ORM_NAME_GUILD_INFO, $guildId);
        $guildPersonNum = $guildInfo->getNum();
        $participantNum = count(explode(',',$guildCompetitionData->getParticipant()));
        //$failTaskNum = $guildCompetitionData->getDelTask() + $guildCompetitionData->getDrop();
        $newPointSpeed = $groupConfig['speed'][0]*$groupConfig['speed'][1] - ($participantNum/$guildPersonNum)*$groupConfig['deduction2'];
//        （公会参赛人数 * deduction2 / 公会总人数）^deduction1
        return $newPointSpeed < 0 ? 0 : $newPointSpeed;
    }

    /**
     * 获得权重奖励
     * @param $giftConf
     * @return array
     */
    public function getRewardArr($giftConf){
        //解析获得道具
        $itemArr = array();
        $randomTimes = $giftConf['randomTimes'];
        $getReward = array();
        $rewardArr = explode(',',$giftConf['randomDropItems']);
        $rewardWeightArr = array();
        $rewardConf = array();
        //制作权重库
        foreach ($rewardArr as $key=>$conf){
            $itemArr = explode(':',$conf);
            $rewardConf[$itemArr[0]] = $itemArr;
            $rewardWeightArr[] = array('item'=>$itemArr[0],'weight'=>$itemArr[2]);
        }

        for ($i = 1; $i <= $randomTimes; $i++){
            $tempItemId = $this->randomTaskIdByWeight($rewardWeightArr)['item'];
            $getReward[$tempItemId] = $rewardConf[$tempItemId][1];
            if ($giftConf['type'] == 1){//随机后，物品剔除
                foreach ($rewardWeightArr as $key=>$data){
                    if ($data['item'] == $tempItemId){
                        unset($rewardWeightArr[$key]);
                    }
                }
            }
        }

        return $getReward;
    }

    /**
     * 格式化任务数据
     * @param $taskData
     * @param $taskConf
     * @param null $key
     * @return array
     */
    public function taskFormatData($taskData,$taskConf,$key=null){
        $taskDatas['taskId'] = $taskData['pos'];//任务位置
        $taskDatas['taskConfigId'] = $taskData['taskId'];//任务索引
        $taskDatas['playerId'] = $taskData['userId'];//任务执行者
        $taskDatas['handleTime'] = $taskData['handleTime'];//玩家接任务的时间
        $taskDatas['itemId'] = $taskData['needItem'];//需要的物品
        $taskDatas['finishNum'] = $taskData['process'];//当前完成的数量
        $taskDatas['totalNum'] = $taskData['needProcess'];//需要完成的总数
        $taskDatas['time'] = $taskData['timeRange'];//完成任务需要的最大时间段
        $taskDatas['score'] = ceil($taskConf['score']*$taskData['needProcess']);//任务完成所获奖励分值
        $taskDatas['startTime'] = $taskData['cdTime'];//该任务可接的时间戳

        return $taskDatas;
    }

    /**
     * 格式化社团竞赛参与公会数据
     * @param $guildId
     * @param $guildCompetitionData
     * @return array
     * @throws SzException
     */
    public function competitionFormatData($guildId,$guildCompetitionData)
    {
        $name = '';
        if ($guildCompetitionData->getIsRob()){
            //获取机器人配置名称
            $robConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_ROBS, $guildCompetitionData->getRobIndex(), true);
            $name = (string)$robConf['robotName'];
        }
        else{
            /**
             * @var GuildInfoVo $guildInfo
             */
            $guildInfo = SzPersister::get()->getVo(null, GameConst::ORM_NAME_GUILD_INFO, $guildId);
            if ($guildInfo){
                $name = (string)$guildInfo->getName();
            }
            else{
                $name = 'Gog'.rand(1,100);
            }
        }

        return array(
            'id' => $guildId,
            'groupId' => $guildCompetitionData->getGroupId(),
            'ai' => $guildCompetitionData->getIsRob(),
            'name' => $name,
            'matchLv' => $guildCompetitionData->getQuality(),
            'score' => $guildCompetitionData->getPoint(),
        );
    }

    /**
     * 格式化社团竞赛公会历史数据
     * @param $quality
     * @param $history
     * @return array
     */
    public function competitionHistoryFormatData($quality,$history)
    {
        return array(
            'matchLv' => $quality,
            'times1' => $history[0] ? $history[0] : 0,
            'times2' => $history[1] ? $history[1] : 0,
            'times3' => $history[2] ? $history[2] : 0
        );
    }

    /**
     * 任务进度添加
     * @param $userId
     * @param $doTask
     * @param $reqTime
     * @param $process
     * @param int $itemId
     * @throws SzException
     */
    public function addCompetitionTaskProcess($userId,$doTask,$reqTime,$process,$itemId=0){
        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
        if ($isOpen != 1){
            return;
        }

        //获取玩家工会竞赛任务数据
        /**
         * @var GuildCompetitionMemberVo $guildCompetitionMemberData
         */
        $guildCompetitionMemberData =  SzPersister::get()->getVo($userId, GameConst::ORM_NAME_UNION_COMPETITION_MEMBER);
        if ($guildCompetitionMemberData){
            //验证任务
            if ($guildCompetitionMemberData->getNowTask()){
                /**
                 * @var ModuleProfileInfoVoList $profileInfoList
                 */
                //获取玩家工会ID
                $profileInfoList = SzPersister::get()->getVoList($userId, ModuleProfileConst::ORM_NAME_PROFILE_INFO);
                $guildId = $profileInfoList->getElement(GameConst::USER_INFO_TYPE_GUILD_ID)->getRawInfo();
                //获取玩家当前正在执行的任务
                /**
                 * @var GuildCompetitionTaskVoList $guildCompetitionTaskList
                 * @var GuildCompetitionTaskVo $guildCompetitionTask
                 */
                $guildCompetitionTaskList = SzPersister::get()->getVoList($guildId, GameConst::ORM_NAME_UNION_COMPETITION_TASK);
                foreach ($guildCompetitionTaskList->toArray() as $key=>$taskData){
                    if ($taskData['userId'] == $userId){
                        $guildCompetitionTask = $guildCompetitionTaskList->getElement($taskData['pos'],false);
                        if ($guildCompetitionTask){
                            $nowProcess = $guildCompetitionTask->getProcess();
                            //验证需要指定提交的任务
                            $taskIndexId = $guildCompetitionTask->getTaskId();
                            $needItem = $guildCompetitionTask->getNeedItem();
                            $taskConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_TASKS, $taskIndexId, true);
                            if ($doTask == GameConst::UNION_COMPETITION_TASK_1){
                                if ($needItem == 0){
                                    return;
                                }
                                else{
                                    if ($needItem != $itemId){
                                        return;
                                    }
                                }
                            }

                            if ($doTask != GameConst::UNION_COMPETITION_TASK_1){//收花特殊处理1,13,14
                                $taskType = $taskConf['taskType'];
                                if ($doTask != $taskType){
                                    return;
                                }
                            }
                            //验证过期，进度，状态等数据进行更新
                            if ($guildCompetitionTask->getHandleTime() + $guildCompetitionTask->getTimeRange() > $reqTime
                                && $guildCompetitionTask->getState() == 1
                                && $nowProcess < $guildCompetitionTask->getNeedProcess()
                            ){
                                //任务进度更新
                                $newProcess = ($nowProcess + $process) > $guildCompetitionTask->getNeedProcess() ? $guildCompetitionTask->getNeedProcess() : ($nowProcess + $process);
                                $guildCompetitionTask->setProcess($newProcess);
                                $guildCompetitionTask->setUpdateTime($reqTime);
                                $guildCompetitionTaskList->updateElement($taskData['pos'],$guildCompetitionTask);
                                SzPersister::get()->setVoList($guildCompetitionTaskList);
                            }
                            return;
                        }
                    }
                }
                return;
            }
            return;
        }
        return;
    }

    /**
     * 玩家主动退出公会or被踢出去进行数据更新
     * @param $userId
     * @param $guildId
     * @param $guildInfo
     * @param $reqTime
     * @throws SzException
     */
    public function quitGuildUpdateData($userId,$guildId,$guildInfo,$reqTime)
    {
        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
        if ($isOpen != 1){
            return;
        }
        //获取玩家参与赛事公用配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)) {
            return;
        }

        //验证是否属于公会赛时间内
        /**
         * @var GuildCompetitionVo $guildCompetitionData
         */
        $guildCompetitionData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
        if (!$guildCompetitionData) {
            return;
        }
        //时间验证
        $startTime = $guildCompetitionData->getCreateTime();
        $endTime = $guildCompetitionData->getEndTime();
        if ($reqTime <= $startTime || $reqTime >= $endTime) {
            return;
        }

        //验证玩家时候属于参赛者
        $participant = json_decode($guildCompetitionData->getParticipant());
        if ($participant == '' || !$participant || empty($participant) || $participant == null) {
            return;
        }

        $participantArr = explode(',', $participant);
        if (!in_array($userId, $participantArr)) {
            return;
        }

        //从参与者中进行删除
        $newPointSpeed = 0;
        $personNum = 0;
        $quality = $guildCompetitionData->getQuality();
        foreach ($participantArr as $key => $uid) {
            if ($uid == $userId) {
                unset($participantArr[$key]);
                //获取玩家工会信息
                /**
                 * @var GuildInfoVo $guildInfo
                 */
                $guildPersonNum = $guildInfo->getNum();
                //（公会参赛人数 * deduction2 / 公会总人数）^deduction1
                $deduction2 = explode(',', $groupConfig['deduction2'])[$quality - 1];
                $deduction1 = explode(',', $groupConfig['deduction1'])[$quality - 1];
                $personNum = count($participantArr);
                $newPointSpeed = ceil(pow((($personNum * $deduction2) / $guildPersonNum), $deduction1));
                break;
            }
        }
        //公共数据进行更新
        $guildCompetitionData->setPointSpeed($newPointSpeed);
        $guildCompetitionData->setParticipant(json_encode(implode(',', $participantArr)));
        $guildCompetitionData->setUpdateTime($reqTime);
        SzPersister::get()->setVo($guildCompetitionData);

        //参赛人数上报
        StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $reqTime, array(
            'clientData' => array(
                'tid' => 'Module:unionCompetition|action:getPersonNum|',
                'item' => $guildId.'&personNum',
                'value' => $personNum
            )
        ));

        //获取玩家工会竞赛任务数据
        /**
         * @var GuildCompetitionTaskVoList $guildCompetitionTaskList
         * @var GuildCompetitionTaskVo $guildCompetitionTask
         */
        $guildCompetitionTaskList = SzPersister::get()->getVoList($guildId, GameConst::ORM_NAME_UNION_COMPETITION_TASK);
        foreach ($guildCompetitionTaskList->toArray() as $key => $taskData) {
            if ($taskData['userId'] == $userId) {
                $guildCompetitionTask = $guildCompetitionTaskList->getElement($taskData['pos'],false);
                $randomTaskConf = $this->getRandomTaskConf($quality);
                if ($randomTaskConf['code'] != 0) {
                    break;
                }
                //刷新任务
                $guildCompetitionTask->setTaskId($randomTaskConf['randomTaskConf']['indexId']);
                $guildCompetitionTask->setNeedItem($randomTaskConf['needItem']);
                $guildCompetitionTask->setNeedProcess($randomTaskConf['needProcess']);
                $guildCompetitionTask->setTimeRange($randomTaskConf['timeRange']);
                $guildCompetitionTask->setProcess(0);
                $guildCompetitionTask->setUserId(0);
                $guildCompetitionTask->setState(0);
                $guildCompetitionTask->setHandleTime(0);
                $guildCompetitionTask->setUpdateTime($reqTime);

                $guildCompetitionTaskList->updateElement($taskData['pos'], $guildCompetitionTask);
                SzPersister::get()->setVoList($guildCompetitionTaskList);
                break;
            }
        }

        //个人数据部分保留
        /**
         * @var GuildCompetitionMemberVo $guildCompetitionMemberData
         */
        $guildCompetitionMemberData = SzPersister::get()->getVo($userId, GameConst::ORM_NAME_UNION_COMPETITION_MEMBER);
        if ($guildCompetitionMemberData) {
            //获取玩家当前正在执行的任务
            $nowTaskId = $guildCompetitionMemberData->getNowTask();
            if ($nowTaskId != 0) {
                //数据更新
                $guildCompetitionMemberData->setNowTask(0);
                $guildCompetitionMemberData->setFailTaskNum($guildCompetitionMemberData->getFailTaskNum() + 1);
                $guildCompetitionMemberData->setUpdateTime($reqTime);
                SzPersister::get()->setVo($guildCompetitionMemberData);
            }

            //记录上一工会推出时间
            /**
             * @var $profileInfoList  ModuleProfileInfoVoList
             * @var ModuleProfileInfoVo $recordGuild
             */
            $profileInfoList = SzPersister::get()->getVoList($userId, ModuleProfileConst::ORM_NAME_PROFILE_INFO);
            //获取玩家的旧工会数据
            $recordGuild = $profileInfoList->getElement(GameConst::USER_INFO_TYPE_LAST_GUILD_MSG,false);

            if (!$recordGuild) {
                $recordGuild = new ModuleProfileInfoVo(
                    $userId,
                    GameConst::USER_INFO_TYPE_LAST_GUILD_MSG,
                    json_encode($guildId.':'.$reqTime),
                    $reqTime,
                    true
                );
                $profileInfoList->addElement($recordGuild);
                $profileInfoList->setElement(GameConst::USER_INFO_TYPE_LAST_GUILD_MSG, $recordGuild);
            } else {
                $recordGuild->setTime($reqTime);
                $recordGuild->setInfo($guildId.':'.$reqTime);
                $profileInfoList->updateElement(GameConst::USER_INFO_TYPE_LAST_GUILD_MSG, $recordGuild);
            }
            SzPersister::get()->setVoList($profileInfoList);
        }

        //删除所拥有的临时头像框
        $this->clearHeadFrameData($userId,$groupConfig,$quality,$reqTime);

        return;
    }

    /**
     * 删除社团竞赛数据
     * @param $userId
     * @param $guildId
     * @param $reqTime
     * @throws SzException
     */
    public function deleteCompetitionData($userId,$guildId,$reqTime)
    {
        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
        if ($isOpen != 1){
            return;
        }

        //获取玩家参与赛事公用配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)) {
            return;
        }

        //验证是否属于公会赛时间内
        /**
         * @var GuildCompetitionVo $guildCompetitionData
         */
        $guildCompetitionData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
        if (!$guildCompetitionData) {
            return;
        }
        //时间验证
        $startTime = $guildCompetitionData->getCreateTime();
        $endTime = $guildCompetitionData->getEndTime();
        if ($reqTime <= $startTime || $reqTime >= $endTime) {
            return;
        }
        $quality = $guildCompetitionData->getQuality();
        $groupId = $guildCompetitionData->getGroupId();

        //小组数据删除&重新入库
        /**
         * @var GuildCompetitionLibraryVo $guildGroupByQualityData
         */
        $guildGroupByQualityData = SzPersister::get()->getVo($quality, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);
        if ($guildGroupByQualityData){
            $guildsArr = array();
            $strKey = null;
            $groupDataStr = explode(';',$guildGroupByQualityData->getGuildsByGroup());
            foreach ($groupDataStr as $key=>$data){
                if (explode(':',$data)[0] == $groupId){
                    $guildsArr = explode(',',(explode(':',$data)[1]));
                    $strKey = $key;
                }
            }

            $newGroupStr = '';
            foreach ($guildsArr as $key=>$gid){
                if ($gid == $guildId){
                    unset($guildsArr[$key]);
                    $newGroupStr = implode(',',$guildsArr);
                    break;
                }
            }

            if (($newGroupStr != '' || $newGroupStr != null) && $strKey != null){
                $groupDataStr[$strKey] = ($groupId).':'.$newGroupStr;
                $newGroup = implode(';',$groupDataStr);
                $guildGroupByQualityData->setGuildsByGroup($newGroup);
                $guildGroupByQualityData->setUpdateTime($reqTime);
                SzPersister::get()->setVo($guildGroupByQualityData);
            }
        }

        //参赛工会库数据删除
        /**
         * @var GuildGroupVo $guildGroupInfo
         */
        $guildGroupInfo = SzPersister::get()->getVo($groupId, GameConst::ORM_NAME_UNION_COMPETITION);
        if ($guildGroupInfo){
            $newRealStr = '';
            $realGroupArr = explode(',',$guildGroupInfo->getRawRealGroup());
            foreach ($realGroupArr as $key=>$gid){
                if ($gid == $guildId){
                    unset($realGroupArr[$key]);
                    $newRealStr = implode(',',$realGroupArr);
                    break;
                }
            }

            if ($newRealStr != '' || $newRealStr != null){
                //更新数据
                $guildGroupInfo->setRealGroup($newRealStr);
                $guildGroupInfo->setUpdateTime($reqTime);
                SzPersister::get()->setVo($guildGroupInfo);
            }
        }

        //进行公共数据删除
        /* @var GuildCompetitionModel $guildCompetitionModel
         */
        $guildCompetitionModel = SzPersister::get()->getModel(GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
        $guildCompetitionData = $guildCompetitionModel->retrieve(null, $guildId);
        $guildCompetitionModel->deleteVoCache($guildCompetitionData);
        $guildCompetitionModel->delete($guildCompetitionData);

        //个人数据删除
        /* @var GuildCompetitionMemberModel $guildCompetitionPersonModel
         * @var GuildCompetitionMemberVo $guildCompetitionMemberData
         */
        $guildCompetitionMemberData = SzPersister::get()->getVo($userId, GameConst::ORM_NAME_UNION_COMPETITION_MEMBER);
        if ($guildCompetitionMemberData){
            $guildCompetitionPersonModel = SzPersister::get()->getModel(GameConst::ORM_NAME_UNION_COMPETITION_MEMBER);
            $guildCompetitionMemberData = $guildCompetitionPersonModel->retrieve(null, $userId);
            $guildCompetitionPersonModel->deleteVoCache($guildCompetitionMemberData);
            $guildCompetitionPersonModel->delete($guildCompetitionMemberData);
        }

        //工会竞赛任务数据删除
        /**
         * @var GuildCompetitionTaskVoList $guildCompetitionTaskList
         * @var GuildCompetitionTaskVo $guildCompetitionTask
         */
        $guildCompetitionTaskList = SzPersister::get()->getVoList($guildId, GameConst::ORM_NAME_UNION_COMPETITION_TASK);
        if ($guildCompetitionTaskList->getListCount() != 0){
            foreach ($guildCompetitionTaskList->toArray() as $key => $taskData) {
                $guildCompetitionTaskList->deleteElement($taskData['pos'], false);
            }
            SzPersister::get()->setVoList($guildCompetitionTaskList);
        }

        //删除工会历史数据
        /**
         * @var GuildCompetitionHistoryVo $guildHistoryInfo
         */
        $guildHistoryInfo = SzPersister::get()->getVo($groupId, GameConst::ORM_NAME_UNION_COMPETITION_HISTORY);
        if ($guildHistoryInfo){
            /* @var GuildCompetitionHistoryModel $guildCompetitionHistoryModel
             */
            $guildCompetitionHistoryModel = SzPersister::get()->getModel(GameConst::ORM_NAME_UNION_COMPETITION_MEMBER);
            $guildHistoryInfo = $guildCompetitionHistoryModel->retrieve(null, $guildId);
            $guildCompetitionHistoryModel->deleteVoCache($guildHistoryInfo);
            $guildCompetitionHistoryModel->delete($guildHistoryInfo);
        }

        //删除所拥有的临时头像框
        $this->clearHeadFrameData($userId,$groupConfig,$quality,$reqTime);

        return;

    }

    /**
     * 删除社团竞赛玩家所获得的头像数据
     * @param $userId
     * @param $groupConfig
     * @param $quality
     * @param $reqTime
     * @throws SzException
     */
    public function clearHeadFrameData($userId,$groupConfig,$quality,$reqTime){
        //删除所拥有的临时头像框
        /**
         * @var $userDressList UserDressVoList
         * @var $userDressData UserDressVo
         */
        $userDressList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_USER_DRESS);
        $userDressData = $userDressList->getElement(GameConst::ITEM_SPECIAL_SMALL_TYPE['Head_frame'],false);
        if ($userDressData){
            $headFrameLibrary = json_decode($userDressData->getStock());
            $headFrameArr = explode(',',$headFrameLibrary);
            $itemId = (int)substr($groupConfig['pictureFrame'][$quality - 1] , 4 , 8);
            $itemStr = '';
            foreach ($headFrameArr as $key1=>$data){
                if ($data == $itemId){
                    unset($headFrameArr[$key1]);
                    break;
                }
            }

            if (empty($headFrameArr)){
                $userDressData->setStock($itemStr);
            }
            else{
                $itemStr = implode(',',$headFrameArr);
                $userDressData->setStock($itemStr);
            }
            $userDressList->updateElement(GameConst::ITEM_SPECIAL_SMALL_TYPE['Head_frame'], $userDressData);
            SzPersister::get()->setVoList($userDressList);
            /**
             * 获取玩家商品数据
             * @var ModuleItemVoList $itemList
             */
            $itemList = SzPersister::get()->getVoList($userId, ModuleItemConst::ORM_NAME_ITEM);
            $itemData = $itemList->getElementsByItemDefId($itemId);
            if ($itemData){
                $itemNum = $itemList->getItemDefCount($itemId);
                if ($itemNum > 0){
                    //消耗头像框
                    GameService::get()->handleEntity($userId, '7401'.$itemId, 1, true, true);
                }
            }
        }

        //设置玩家当前的头像框数据
        /**
         * @var ModuleProfileVo $profileInfo
         * @var ModuleProfileInfoVoList $profileInfoList
         */
        $profileInfoList = SzPersister::get()->getVoList($userId, ModuleProfileConst::ORM_NAME_PROFILE_INFO);
        $profileInfo = $profileInfoList->getElement(GameConst::USER_INFO_TYPE_HEAD_FRAME, false);
        //设置当前使用的头像框
        if ($profileInfo) {
            $profileInfo->setInfo(0);
            $profileInfo->setTime($reqTime);
            $profileInfoList->updateElement(GameConst::USER_INFO_TYPE_HEAD_FRAME, $profileInfo);
            SzPersister::get()->setVoList($profileInfoList);
        }

        return;
    }

    /**
     * 记录获取
     * @param $guildId
     * @return array
     * @throws SzException
     */
    public function competitionRecord($guildId)
    {
        $res = array(
            'code' => 0,
            'record' => array()
        );

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
        if ($isOpen != 1){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//开关没有开启
            return $res;
        }

        //获取玩家参与赛事公用配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['CONFIG_NOT_EXIST'];//配置不存在
            return $res;
        }

        $record = array();
        /**
         * @var $competitionRecord GuildCompetitionRecordVo
         */
        $competitionRecord = SzPersister::get()->getVoList($guildId, GameConst::ORM_NAME_UNION_COMPETITION_RECORD);
        if ($competitionRecord){
            $record = $competitionRecord->toArray();
        }
        else{
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_113'];//工会没有参加上一届竞赛
            return $res;
        }

        $res['record'] = $record;
        return $res;
    }

    /**
     * 更新玩家道具数据
     * @param $userId
     * @param $guildId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function getItemsNum($userId,$guildId,$reqTime)
    {
        $res = array(
            'code' => 0,
            'nextRewardTime' => 0,
            'guildScore' => 0,
            'items' =>array()
        );

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
        if ($isOpen != 1){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//开关没有开启
            return $res;
        }

        //获取工会公用分组配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            return $res;
        }

        //结算时刻请求返回
        $canRequest = $this->checkLastHour($groupConfig,$reqTime);
        if (!$canRequest){
            $res['code'] = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_114'];//下一届未开启
            return $res;
        }

        //获取工会的公共数据
        /**
         * @var GuildCompetitionVo $guildCompetitionData
         */
        $guildCompetitionData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
        if (!$guildCompetitionData){
            return $res;
        }
        //时间验证
        $startTime = $guildCompetitionData->getCreateTime();
        $endTime = $guildCompetitionData->getEndTime();
        if ($reqTime <= $startTime || $reqTime >= $endTime){
            return $res;
        }

        //获取工会所有参赛人员
        $personStr = json_decode($guildCompetitionData->getParticipant());
        $isJoin = 0;
        if ($personStr != ''){
            $guildMembers = explode(',',$personStr);
            //发放旗帜给每个社员
            foreach ($guildMembers as $uid){
                if ($uid == $userId){
                    $isJoin = 1;
                    break;
                }
            }
        }

        if ($isJoin == 0){
            return $res;
        }

        $res['nextRewardTime'] = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_HOUR_SEND) == 0 ? 0 : $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_HOUR_SEND);
        $res['guildScore'] = $guildCompetitionData->getPoint();

        $itemNum = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_HOUR_SEND_ITEM.$guildId) == 0 ? 0 : $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_HOUR_SEND_ITEM.$guildId);
        if ($itemNum != 0){
            $res['items'] = array(
                GameConst::UNION_COMPETITION_GET_FLAG => $itemNum,
            );
        }

        return $res;
    }

    /**
     * 数据结算紧急删除工具
     */
    public function dataSettlementTool(){
        $serverTime = GameService::get()->getReqTime();
        //获取杂项配置表配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            error_log('******社团赛杂项配置表不存在******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionSettlementToolDel.log');
            return;
        }

        //获取本届各品质赛事参与的工会
        $goldErrStr = "";
        //黄金品质结算
        $goldSuc = $this->guildDel($goldErrStr,GameConst::UNION_COMPETITION_GOLD,$groupConfig,$serverTime);
        error_log('******黄金品质结算结果:【'.$goldSuc.'】'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionSettlementToolDel.log');

        $silverErrStr = "2:1847,1047,1042,1118,1793,1100,2408,1391,1641,2815;3:2312,2331,3108,1661,1289,1040,1347,2091,1893,1497;4:2053,1704,1459,1824,1185,2223,1045,1285,1498,1716;5:1072,1830,1156,1190,1252,1191,2299,1663,1443,1650;6:1083,1168,1555,1245,2443,2504,1288,1480,1975,1419;7:1076,1071,1159,1786,1394,1315,1400,1854,1488,1804;8:2132,1052,1679,1213,1686,1996,1813,1046,1371,1520;9:1030,2410,1126,1609,1531,1309,2190,1086,1536,1832;10:1363,1431,1197,1307,1145,2843,2563,1264,1775,1151;11:1053,1833,2314,1737,1711,2322,1019,2948,1761,1308;12:1722,1049,1034,1068,1212,1117,1792,1924,1795,1449;13:1028,1051,2418,1069,1575,2289,1503,1140,1648,1255;14:1038,1025,1420,1210,2925,1606,1089,1521,1593,1794;15:1111,1041,1472,2320,1258,2292,1139,1442,1121,2358;16:1061,1127,1489,1274,1079,1355,1176,2328,1020,2126;17:1057,1027,1314,1137,1644,1577,1781,1949,1817,1853;18:1173,1927,3085,1543,1056,1026,1048,1717,1199,1601;19:1098,1066,1597,2205,1262,1812,2474,1408,1413,1208;20:1097,1427,1029,1082,2345,1075,1739,1348,2051,1304;21:1043,1179,1864,1058,1600,1479,1275,1621,1734,1999;22:1294,1153,1070,2101,1729,1357,1366,1411,1578,1845;23:1120,2040,1129,1695,1483,1611,2514,2384,1375,1460;24:1187,2232,1299,1948,1946,1502,1219,1059,1302,2055;25:1180,1143,1150,1861,1033,1583,1541,1333,1358,1698;26:1062,1628,1368,1320,1253,1217,1916,1078,1573,1772;27:2491,1466,1039,1031,2036,1192,2704,1633,1660,1849;28:1112,1123,1081,2237,1256,2407,1238,2327,1382,1324;29:1096,1138,1044,1321,2135,1206,1122,1339,1467,2288;30:1142,1125,1215,1227,1818,1023,1884,2584,1429,1369;31:1065,1519,1569,1613,1740,1862,1214,1565,1931,2220;32:1021,1032,1200,2631,1651,1080,1036,1547,1779,1582;33:1471,1063,1372,1247,1128,1814,2108,1617,1035,1747;34:1146,1074,1351,1024,1381,3031,-22,-21,-23,-24";
        //白银品质结算
        $silverSuc = $this->guildDel($silverErrStr,GameConst::UNION_COMPETITION_SILVER,$groupConfig,$serverTime);
        error_log('******白银品质结算结果:【'.$silverSuc.'】'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionSettlementToolDel.log');

        $bronzeErrStr = "";
        //青铜品质结算
        $bronzeSuc = $this->guildDel($bronzeErrStr,GameConst::UNION_COMPETITION_BRONZE,$groupConfig,$serverTime);
        error_log('******青铜品质结算结果:【'.$bronzeSuc.'】'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionSettlementToolDel.log');

        error_log('******社团竞赛数据结算结束！！！'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionSettlementToolDel.log');

        return;
    }

    /**
     * 历史数据更新或者创建del工具
     * @param $errStr
     * @param $quality
     * @param $groupConfig
     * @param $reqTime
     * @return bool
     * @throws SzException
     */
    public function guildDel($errStr,$quality,$groupConfig,$reqTime){
        error_log('******社团竞赛数据结算*****品质赛事为:【'.$quality.'】的数据开始！！！！******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionSettlementToolDel.log');
        /**
         * @var GuildCompetitionLibraryVo $libraryInfo
         */
        if ($errStr != ''){
            $guildStrArr = explode(';',$errStr);
            foreach ($guildStrArr as $key=>$groupStr){
                $guildsArr = explode(',',(explode(':',$groupStr)[1]));
                $groupId = explode(':',$groupStr)[0];
                if (!empty($guildsArr)){
                    foreach ($guildsArr as $key1=>$guildId){
                        if ($guildId < 0){
                            //删除公共数据
                            /* @var GuildCompetitionModel $guildCompetitionRobModel
                             */
                            //获取工会工会数据
                            /**
                             * @var GuildCompetitionVo $guildCompetitionRobData
                             */
                            $guildCompetitionRobData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
                            if ($guildCompetitionRobData){
                                error_log('******社团ID为:【'.$guildId.'】------删除机器人数据开始******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionSettlementToolDel.log');
                                $guildCompetitionRobModel = SzPersister::get()->getModel(GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
                                $guildCompetitionRobData = $guildCompetitionRobModel->retrieve(null, $guildId);
                                $guildCompetitionRobModel->deleteVoCache($guildCompetitionRobData);
                                $guildCompetitionRobModel->delete($guildCompetitionRobData);
                                error_log('******社团ID为:【'.$guildId.'】------删除机器人数据数据结束******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionSettlementToolDel.log');
                            }
                            continue;
                        }

                        //获取工会工会数据
                        /**
                         * @var GuildCompetitionVo $guildCompetitionData
                         */
                        $guildCompetitionData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
                        if (!$guildCompetitionData){
                            error_log('******社团ID为:【'.$guildId.'】------公共数据为空******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionSettlementToolDel.log');
                            continue;
                        }

                        //删除参与者数据
                        error_log('******社团ID为:【'.$guildId.'】------删除参与者数据开始******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionSettlementToolDel.log');
                        if (json_decode($guildCompetitionData->getParticipant()) != ''){
                            $participantArr = explode(',',json_decode($guildCompetitionData->getParticipant()));
                            if (!empty($participantArr) && count($participantArr) != 0){
                                foreach ($participantArr as $uid){
                                    /**
                                     * @var GuildCompetitionMemberVo $guildCompetitionMemberData
                                     */
                                    //获取玩家社团竞赛个人数据删除
                                    $guildCompetitionMemberData =  SzPersister::get()->getVo($uid, GameConst::ORM_NAME_UNION_COMPETITION_MEMBER);
                                    if ($guildCompetitionMemberData){
                                        /* @var GuildCompetitionMemberModel $guildCompetitionPersonModel
                                         */
                                        $guildCompetitionPersonModel = SzPersister::get()->getModel(GameConst::ORM_NAME_UNION_COMPETITION_MEMBER);
                                        $guildCompetitionMemberData = $guildCompetitionPersonModel->retrieve(null, $uid);
                                        $guildCompetitionPersonModel->deleteVoCache($guildCompetitionMemberData);
                                        $guildCompetitionPersonModel->delete($guildCompetitionMemberData);
                                    }
                                    //删除所拥有的临时头像框
                                    $this->clearHeadFrameData($uid,$groupConfig,$quality,$reqTime);
                                }
                            }
                        }
                        else{
                            error_log('******社团ID为:【'.$guildId.'】------没有参与者参与本届工会竞赛******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionSettlementToolDel.log');
                        }
                        error_log('******社团ID为:【'.$guildId.'】------删除参与者数据结束******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionSettlementToolDel.log');

                        //删除工会任务数据
                        /**
                         * @var GuildCompetitionTaskVoList $guildCompetitionTaskList
                         * @var GuildCompetitionTaskVo $guildCompetitionTask
                         */
                        error_log('******社团ID为:【'.$guildId.'】------删除工会任务数据开始******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionSettlementToolDel.log');
                        $guildCompetitionTaskList = SzPersister::get()->getVoList($guildId, GameConst::ORM_NAME_UNION_COMPETITION_TASK);
                        if ($guildCompetitionTaskList->getListCount() != 0){
                            foreach ($guildCompetitionTaskList->toArray() as $key3 => $taskData) {
                                $guildCompetitionTaskList->deleteElement($taskData['pos'], false);
                            }
                        }
                        SzPersister::get()->setVoList($guildCompetitionTaskList);
                        error_log('******社团ID为:【'.$guildId.'】------删除工会任务数据结束******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionSettlementToolDel.log');

                        //删除公共数据
                        /* @var GuildCompetitionModel $guildCompetitionModel
                         */
                        error_log('******社团ID为:【'.$guildId.'】------删除公共数据数据开始******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionSettlementToolDel.log');
                        $guildCompetitionModel = SzPersister::get()->getModel(GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
                        $guildCompetitionData = $guildCompetitionModel->retrieve(null, $guildId);
                        $guildCompetitionModel->deleteVoCache($guildCompetitionData);
                        $guildCompetitionModel->delete($guildCompetitionData);
                        error_log('******社团ID为:【'.$guildId.'】------删除公共数据数据结束******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionSettlementToolDel.log');
                    }

                    //删除小组数据
                    error_log('******小组ID为:【'.$groupId.'】------删除小组数据开始******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionSettlementToolDel.log');
                    /**
                     * @var GuildGroupVo $guildGroupInfo
                     */
                    $guildGroupInfo = SzPersister::get()->getVo($groupId, GameConst::ORM_NAME_UNION_COMPETITION);
                    if ($guildGroupInfo){
                        /* @var GuildGroupModel $guildGroupModel
                         */
                        $guildGroupModel = SzPersister::get()->getModel(GameConst::ORM_NAME_UNION_COMPETITION);
                        $guildGroupInfo = $guildGroupModel->retrieve(null, $groupId);
                        $guildGroupModel->deleteVoCache($guildGroupInfo);
                        $guildGroupModel->delete($guildGroupInfo);
                    }
                    error_log('******小组ID为:【'.$groupId.'】------删除小组数据结束******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionSettlementToolDel.log');
                }
            }
        }
        else{
            error_log('******品质为:【'.$quality.'】的错误数据为空******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionSettlementToolDel.log');
        }

        return true;
    }

    /**
     * 准备数据生成紧急工具
     */
    public function repairTool()
    {
        error_log('******线上数据修复开始******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionRepair.log');
//        //设置各阶段时间
//        $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_START_TIME,$nextStartTime);
//        $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_END_TIME,$endTime);
//        $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_SUSPENSION_TIME,$endTime - 86400);
//        $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_SETTLEMENT_TIME,$endTime - 3600);

        //获取工会公用分组配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            error_log('******社团赛杂项配置表不存在******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionRepair.log');
            return;
        }

//        $goldGroupStr = "1:5543,1175,6178,2511,2922,1319,1095,1094,1511,7307;2:6376,7756,1120,5253,1171,1163,5959,1587,1571,7143;3:2535,8823,1034,1834,1220,4636,1064,1638,1019,1383;4:1391,5814,1433,2451,1624,5407,1692,1030,1561,1025;5:1147,1078,4044,1608,1098,2488,5166,4855,1053,1782;6:3034,1144,4652,7261,8110,1195,5945,1477,2208,1575;7:1431,1490,1945,1037,1530,2133,1206,2840,3630,6802;8:6748,1150,1232,7054,3214,1664,1491,9105,5463,1569;9:3088,2386,1599,8179,6306,4637,5947,3433,6302,2548;10:2883,1861,1123,1050,1645,3891,2730,5751,2299,1660;11:1051,6005,4224,2536,1623,7656,1427,1164,5762,1916;12:2023,7920,3226,2553,1139,6159,1805,2478,5413,2779;13:1466,1259,8613,1081,1024,1930,3617,1272,1695,6258;14:3112,1165,1093,1639,1450,6752,1831,1548,2457,6266;15:7689,5861,1444,1678,1159,5942,8114,3910,6721,1089;16:7262,1008,1166,1161,7067,2094,1365,1769,1514,7765;17:2153,4940,5753,1486,2057,1385,2273,1502,5686,4220;18:1469,1112,1146,7256,7853,1449,1042,1032,1675,5432;19:6981,1031,1786,6286,3697,4683,1745,2801,5402,1059;20:4034,1066,1516,1290,1715,1033,8827,1366,1661,2363;21:1035,1313,2957,2335,6522,3435,1506,1012,1435,1602;22:2657,5243,2676,1007,1410,8753,2015,2146,2886,1473;23:8290,1393,1107,1205,1396,8211,1679,1598,1686,6922;24:1015,1559,1565,2044,2032,1850,2468,4790,1442,5968;25:2260,1228,7457,5724,1309,1013,1016,7076,1578,6291;26:3372,2955,5073,1451,3591,2252,2180,2236,2351,1005;27:1084,4203,7717,1185,1982,2058,4697,7319,4064,1759;28:5906,1544,2000,1357,2461,1092,1275,5679,2008,3028;29:2978,3422,1712,1065,9069,1508,6749,1017,3716,4896;30:1614,5493,3755,3854,4807,1768,2949,2482,-31,-32";
//
//        if ($goldGroupStr != ''){
//            error_log('******黄金组修复开始******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionRepair.log');
//            $this->createTool($goldGroupStr,GameConst::UNION_COMPETITION_GOLD,$groupConfig,1573574401,1574179200);
//            error_log('******黄金组修复结束******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionRepair.log');
//        }

//        $silverGroupStr = "31:1709,1197,1880,1103,1425,1489,2425,1980,1603,1068;32:2196,1842,1408,1187,1257,1080,1141,1260,6185,1401;33:1115,1190,6666,3824,1888,1121,1069,1870,7412,2020;34:1135,1406,1102,1642,2006,3992,3257,1101,6968,1510;35:1215,1459,1338,1217,1293,1006,1049,1282,1957,1145;36:1113,9098,1953,1173,3736,1399,2277,1750,1620,1574;37:1952,1258,1859,1643,1753,3204,7294,3447,1237,1216;38:1422,1845,1281,1668,5548,4413,3578,1390,2086,1386;39:2035,1188,3947,1285,1198,1793,2490,2422,1045,2365;40:1291,2132,6323,1253,1134,1597,1392,1156,2404,1504;41:1515,2915,1589,1817,1060,3588,1659,6816,2880,4847;42:4330,7966,1360,2601,1432,2909,4843,1619,3183,1476;43:2671,3134,1046,1246,1226,1440,7278,1592,1702,1191;44:1106,8159,2294,1265,3726,5448,5268,1667,1799,2174;45:1497,1776,1317,5421,1011,1284,1322,1149,2559,1428;46:1368,7469,1904,4487,7758,3078,1230,1137,2326,1915;47:1501,1039,2310,1622,1359,1532,2227,1020,4891,4868;48:1047,1110,1452,1099,1132,2077,1528,1835,1631,1283;49:1896,1621,1720,1326,1243,1211,3085,6358,1437,1130;50:3066,1876,1074,1222,2556,1310,1525,7904,6554,1204;51:1495,1062,1388,2362,1320,1071,4876,1127,1178,2266;52:1023,1009,1746,1407,2551,2742,6885,1521,1629,2956;53:1235,2074,1086,3368,1910,1494,1312,1018,1568,5155;54:1180,1955,1117,3075,1055,1758,1225,1174,1208,4949;55:1292,3328,2104,2866,1783,1617,2449,2019,1552,4100;56:1956,1500,2308,2235,2314,2215,1920,1268,1808,8793;57:2116,8168,1306,1072,1054,1201,1705,1868,1551,1932;58:4824,7191,1997,1154,1710,4170,2426,2048,2858,1488;59:1374,1295,1342,1082,1752,1517,1448,1369,1177,1155;60:1070,4119,1276,2025,4293,1547,2244,1914,3224,1684;61:1152,3618,1302,5136,1199,1725,1336,2926,1160,1151;62:1231,2224,1088,1677,1520,7128,1118,3145,1539,1108;63:1418,2197,7593,1186,1090,1096,1067,1938,1116,2283;64:8866,1460,1153,2136,2087,5683,1041,1524,3570,1168;65:1052,7903,1210,1100,1267,2287,1184,1328,1129,1244;66:1364,1735,2346,1330,1247,1582,1162,2097,5807,3016;67:1056,1872,1128,1140,1288,1370,1803,1596,1318,1736;68:1203,1907,3341,6417,4301,1063,1148,7111,1104,2930;69:7365,1837,3469,1763,6022,1848,2066,1169,6146,5496;70:1402,5825,1858,1286,1409,1091,-21,-22,-23,-24";
//
//        if ($silverGroupStr != ''){
//            error_log('******白银组修复开始******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionRepair.log');
//            $this->createTool($silverGroupStr,GameConst::UNION_COMPETITION_SILVER,$groupConfig,1573574401,1574179200);
//            error_log('******白银组修复结束******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionRepair.log');
//        }

        $bronzeGroupStr = "71:2131,5041,2027,4077,1296,1332,1595,3404,2124,1307;72:3894,1377,1464,1564,8357,1119,4021,4911,1014,1124;73:1287,1176,2098,1654,1999,1126,8745,4657,6616,9678;74:1229,1248,1181,1867,1058,4640,1158,2350,2062,7700;75:1075,6805,1626,1048,1394,2712,1971,1347,2826,8024;76:1641,1636,1076,1172,1254,1968,3548,1505,1131,9870;77:6334,2222,1183,1901,2004,2264,6208,1125,1036,7333;78:1323,1731,3135,1038,1085,1829,5385,1241,2316,8436;79:2063,1339,2079,2166,2099,1044,1785,1721,1351,7035;80:7534,1344,9384,1541,2508,3223,1361,1670,1280,7987;81:1492,1542,5907,8757,3192,2040,1682,1372,2503,6580;82:3333,1580,2082,2459,1182,1960,1892,2371,3739,4836;83:1810,1839,1555,1266,1446,1114,5987,7963,5355,9399;84:1844,1637,1650,3635,2239,4069,2270,2134,1240,9007;85:1656,2774,1523,2368,2592,2038,1509,1157,1478,2278;86:1787,9113,1170,1194,1212,2093,1700,3323,3479,7781;87:1519,2495,2777,6283,3202,4850,1652,8167,2854,2893;88:1214,1585,3236,1279,1618,2243,3000,1299,1471,1562;89:1371,1202,2081,1457,2080,2145,7514,1109,1329,7215;90:2037,1087,1911,1167,2397,1455,1352,1470,9811,4770;91:3167,1713,7245,1527,4650,2448,1507,1073,8428,9871;92:2114,1057,1604,2003,1040,1443,1881,2375,2416,6769;93:1249,1606,1811,1227,2258,1223,3261,1398,5049,8578;94:2178,1472,1355,1219,1400,1847,1403,5369,1423,1579;95:1965,5359,1685,1325,2964,1669,1300,1790,3286,5412;96:3667,5834,1061,1411,4742,1261,1518,2593,9793,6620;97:1468,1356,2107,3604,1179,2322,8324,1772,1207,2285;98:2112,5238,1445,1484,1441,1413,1218,1666,2329,9319;99:6007,1533,1462,1697,1899,1503,2265,1333,2582,2118;100:1278,1316,1830,1305,1797,7315,1583,7777,9550,9745;101:1436,1255,2076,1557,2046,1262,1558,6852,5805,3675;102:7726,1122,5095,1193,1474,2028,1774,1043,2010,5745;103:2263,7133,1964,3999,1331,1294,1665,1496,6624,9382;104:4142,5504,1083,2288,1234,6762,-11,-12,-13,-14";

        if ($bronzeGroupStr != ''){
            error_log('******青铜组修复开始******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionRepair.log');
            $this->createTool($bronzeGroupStr,GameConst::UNION_COMPETITION_BRONZE,$groupConfig,1573574401,1574179200);
            error_log('******青铜组修复结束******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionRepair.log');
        }


        error_log('******线上数据修复结束******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionRepair.log');
        return;
    }

    /**
     * 生成小组数据工具1
     * @param $groupStr
     * @param $quality
     * @param $groupConfig
     * @param $serverTime
     * @param $endTime
     * @throws SzException
     */
    public function createTool($groupStr,$quality,$groupConfig,$serverTime,$endTime)
    {
        //获取机器人配置表
        $robShowArr = array();
        $configs = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_ROBS, null, true);
        foreach ($configs as $key=>$conf){
            if ($conf['leagueMatch'] == $quality){
                $robShowArr[] = $conf['indexId'];
            }
            if (count($robShowArr) == 9){
                break;
            }
        }

        $qualityTaskConf = array();
        $taskShowWeightArr = array();
        //获取任务配置表
        $canCreateNum = $groupConfig['taskNum'][$quality - 1];
        $configTasks = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_TASKS, null, true);
        foreach ($configTasks as $key1=>$conf1){
            if ($conf1['leagueMatch'] == $quality){
                $qualityTaskConf[$conf1['indexId']] = $conf1;
                $taskShowWeightArr[] = array('tid'=>$conf1['indexId'],'weight'=>$conf1['weights']);
            }
            if (count($qualityTaskConf) == $canCreateNum){
                break;
            }
        }

        $groupArr = explode(';',$groupStr);
        foreach ($groupArr as $key2=>$str){
            //创建分组数据
            $temp = explode(':',$str);
            $group = $temp[0];
            $groupStr = $temp[1];
            $guilds = explode(',',$groupStr);
            $endGroupRob = 0;
            $realGroup = $groupStr;
            $robGroup = '';

            if ($group == 10){
                $endGroupRob = 1;
                $realGroup = '1197,1049,1025,1489,1864,2040,1112,1215,1519';
                $robGroup = '-31';
            }
            if ($group == 24){
                $endGroupRob = 1;
                $realGroup = '2223';
                $robGroup = '-21,-22,-23,-24,-25,-26,-27,-28,-29';
            }

            //生成小组数据
            /**
             * @var GuildGroupVo $guildGroupInfo
             */
            $guildGroupInfo = SzPersister::get()->getVo($group, GameConst::ORM_NAME_UNION_COMPETITION);
            if (!$guildGroupInfo){
                $guildGroupInfo = new GuildGroupVo(
                    $group,
                    $quality,
                    $endGroupRob,
                    json_encode($realGroup),
                    json_encode($robGroup),
                    $serverTime,
                    $serverTime,
                    $endTime,
                    true
                );
            }
            //更新数据
            SzPersister::get()->setVo($guildGroupInfo);
            error_log('------修复小组【:'.($group).'】成功------'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionRepair.log');

            //生成工会公共数据
            foreach ($guilds as $key3=>$guildId){
                $isRob = $guildId < 0 ? 1 : 0;
                $robIndex = 0;
                if ($isRob){
                    $robIndex = $robShowArr[array_rand($robShowArr)];
                }
                //公共数据生成
                $guildCompetition = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
                if (!$guildCompetition){
                    $guildCompetition = new GuildCompetitionVo(
                        $guildId,
                        $group,
                        $quality,
                        0,
                        0,
                        0,
                        0,
                        0,
                        $isRob,
                        $robIndex,
                        0,
                        json_encode(''),
                        $serverTime,
                        $serverTime,
                        $endTime,
                        true
                    );
                    //更新数据
                    SzPersister::get()->setVo($guildCompetition);
                }
                error_log('******社团ID:'.$guildId.'公共数据修复成功******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionRepair.log');
                if ($guildId > 0){
                    //记录真实工会赛事品质
                    StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, 1572969601, array(
                        'clientData' => array(
                            'tid' => 'Module:unionCompetition|action:Repair|',
                            'item' => $guildId.'&'.$quality,
                            'value' => 1
                        )
                    ));

                    //生成该工会的任务数据
                    /**
                     * @var GuildCompetitionTaskVoList $guildCompetitionTaskList
                     * @var GuildCompetitionTaskVo $guildCompetitionTask
                     */
                    $guildCompetitionTaskList = SzPersister::get()->getVoList($guildId, GameConst::ORM_NAME_UNION_COMPETITION_TASK);
                    if ($guildCompetitionTaskList->getListCount() == 0){
                        for ($pos = 1 ; $pos <= $canCreateNum ; $pos++){
                            $taskIndexId = $this->randomTaskIdByWeight($taskShowWeightArr)['tid'];
                            $taskConf = $qualityTaskConf[$taskIndexId];
                            if (empty($taskConf)){
                                error_log('******社团竞赛任务修复出错******taskIndexId:'.$taskIndexId."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionRepair.log');
                                continue;
                            }
                            $needItem = 0;
                            if ($taskConf['taskitems'] != '0'){
                                $items = explode(';',$taskConf['taskitems']);
                                $needItem = $items[array_rand($items)];
                            }

                            $needProcess = rand($taskConf['randomNum'][0],$taskConf['randomNum'][1]);
                            $timeRange = $needProcess*$taskConf['limitedTime'];
                            $guildCompetitionTask = new GuildCompetitionTaskVo(
                                $guildId,//工会id
                                $pos,//位置
                                $taskConf['indexId'],//任务索引
                                $needItem,//指定物品
                                $needProcess,//目标进度
                                $timeRange,//需求时间段内完成
                                0,//当前完成进度
                                0,//用户ID
                                0,//任务状态
                                0,//接任务时间
                                0,//cd时间
                                $serverTime,
                                $serverTime,
                                $endTime,
                                true
                            );
                            $guildCompetitionTaskList->addElement($guildCompetitionTask);
                            $guildCompetitionTaskList->setElement($pos,$guildCompetitionTask);
                        }
                        SzPersister::get()->setVoList($guildCompetitionTaskList);
                        error_log('******社团ID:'.$guildId.'任务数据修复成功******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionRepair.log');
                    }
                }
            }
        }
        return;
    }

    /**
     * 校验结算时间
     * @param $groupConfig
     * @param $reqTime
     * @return bool
     */
    public function checkLastHour($groupConfig,$reqTime){
        //获取当前时间属于周几
        $weekDay = date("w",$reqTime);
        //获取当前时间属于周几
        $hour = (int)date("H",$reqTime);

        if ($weekDay == $groupConfig['matchTime1'] - 1 && $hour == 23){
            return false;
        }
        else{
            return true;
        }
    }

    /**
     * 准备数据生成青铜
     */
    public function prepareDataGeneration1()
    {
        $testTime1 = time();
        error_log('******青铜初始化时间：'.$testTime1.'***准确时间:'.date("Y-m-d H:i:s",$testTime1)."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
        if ($isOpen != 1){
            error_log('******社团竞赛系统没有开启！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }

        error_log('******青铜数据初始化开始！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        //获取当前请求时间
        $serverTime = GameService::get()->getReqTime();
        //获取当前时间属于周几
        $weekDay = date("w",$serverTime);
        error_log('******星期'.$weekDay."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        //获取工会公用分组配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            error_log('******杂项配置表不存在******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }

        //获取当前时间属于周几
        $hour = (int)date("H",$serverTime);
        //验证开启时段正确
        if ($weekDay != $groupConfig['matchTime1']){
            error_log('******青铜初始化在每周3执行******timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }
        if ($weekDay == $groupConfig['matchTime1'] && $hour != 11){
            error_log('******青铜初始化只会在每周3上午11点50执行******timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }

        //获取服务器所有的工会进行分组
        $serversConfigs = SzConfig::get()->loadAppConfig('database', 'MySql');
        $instance = new SzMySqlDb($serversConfigs[0]);
        $originalGuildArr = $instance->select("SELECT `id`  FROM `ft_guild_info` WHERE `num` >= ".$groupConfig['buddyNum']);
        $guildArr = array();
        if (!empty($originalGuildArr)){
            foreach ($originalGuildArr as $k=>$data){
                $guildArr[] = $data['id'];
            }
        }

        $guildsNum = count($guildArr);
        error_log('******公会数量为:'.$guildsNum."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        if (empty($guildArr) || $guildsNum == 0){
            error_log('******公会数量为0'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }

        //  正式的时候需要开启
        $nextStartTime = $serverTime + 5*60 - 1;
        //数据结构准备
        $robGuildIdStart = 1;//机器人工会id，之后需要转换为负数以作区分
        $endTime = $nextStartTime + $groupConfig['matchTime2'];//当前赛事失效时间

        $flag = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_BRONZE_FLAG);
        if ($flag == 1){//数据已经生成
            error_log('******青铜已经生成！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }
        else{//非首次开启社团竞赛
            //晋级名额及降级名额
            $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_BRONZE_FLAG,1);
//                $up = $groupConfig['promotion'][0];
//                $down = $groupConfig['promotion'][1];

            $gup = $groupConfig['goldPromotion'][0];
            $gdown = $groupConfig['goldPromotion'][1];
            $sup = $groupConfig['silverPromotion'][0];
            $sdown = $groupConfig['silverPromotion'][1];
            $bup = $groupConfig['copperPromotion'][0];
            $bdown = $groupConfig['copperPromotion'][1];
            //获取上一届排序备份数据数据
            /**
             * @var GuildCompetitionLibraryVo $goldLibraryInfo
             * @var GuildCompetitionLibraryVo $silverLibraryInfo
             * @var GuildCompetitionLibraryVo $bronzeLibraryInfo
             */
            $goldLibraryInfo =  SzPersister::get()->getVo(GameConst::UNION_COMPETITION_GOLD, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);
            $silverLibraryInfo =  SzPersister::get()->getVo(GameConst::UNION_COMPETITION_SILVER, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);
            $bronzeLibraryInfo =  SzPersister::get()->getVo(GameConst::UNION_COMPETITION_BRONZE, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);

            /**
             * @var GuildCompetitionBackVo $goldBackInfo
             * @var GuildCompetitionBackVo $silverBackInfo
             * @var GuildCompetitionBackVo $bronzeBackInfo
             */
            $goldBackInfo = SzPersister::get()->getVo(GameConst::UNION_COMPETITION_GOLD, GameConst::ORM_NAME_UNION_COMPETITION_BACKUPS);
            $silverBackInfo = SzPersister::get()->getVo(GameConst::UNION_COMPETITION_SILVER, GameConst::ORM_NAME_UNION_COMPETITION_BACKUPS);
            $bronzeBackInfo = SzPersister::get()->getVo(GameConst::UNION_COMPETITION_BRONZE, GameConst::ORM_NAME_UNION_COMPETITION_BACKUPS);

            if (!$goldLibraryInfo || !$silverLibraryInfo || !$bronzeLibraryInfo){
                error_log('******工会分组库数据丢失******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                return;
            }

            //黄金小组调整
            $goldPreGuildArr = $this->shuntGroup($goldBackInfo,$gup,$gdown,$groupConfig,GameConst::UNION_COMPETITION_GOLD);
            //白银小组调整
            $silverPreGuildArr = $this->shuntGroup($silverBackInfo,$sup,$sdown,$groupConfig,GameConst::UNION_COMPETITION_SILVER);
            //青铜小组调整
            $bronzePreGuildArr = $this->shuntGroup($bronzeBackInfo,$bup,$bdown,$groupConfig,GameConst::UNION_COMPETITION_BRONZE);

            //进行工会重组
            if (!empty($silverPreGuildArr['toGold'])){//黄金赛事
                $goldGroupArr = array_merge($goldPreGuildArr['left'],$silverPreGuildArr['toGold']);
            }
            else{
                $goldGroupArr = $goldPreGuildArr['left'];
            }

            if (empty($goldPreGuildArr['toSilver']) && empty($bronzePreGuildArr['toSilver'])){//白银赛事
                $silverGroupArr = $silverPreGuildArr['left'];
            }
            else{
                $temp = array_merge($silverPreGuildArr['left'],$goldPreGuildArr['toSilver']);
                $silverGroupArr = array_merge($temp,$bronzePreGuildArr['toSilver']);
            }

            if (!empty($silverPreGuildArr['toBronze'])){//青铜赛事
                $bronzeGroupArr = array_merge($bronzePreGuildArr['left'],$silverPreGuildArr['toBronze']);
            }
            else{
                $bronzeGroupArr = $bronzePreGuildArr['left'];
            }

            //新参加的社团添加到青铜模块
            foreach ($guildArr as $key=>$value){
                if (!in_array($value,$goldGroupArr) && !in_array($value,$silverGroupArr) && !in_array($value,$bronzeGroupArr)){
                    $bronzeGroupArr[] = $value;
                }
            }

            if (empty($goldGroupArr)){
                error_log('******黄金赛事分组库为空******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                return;
            }
            if (empty($silverGroupArr)){
                error_log('******白银赛事分组库为空******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                return;
            }
            if (empty($bronzeGroupArr)){
                error_log('******青铜赛事分组库为空******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                return;
            }

            $newGoldStructure = $this->randomGroup($goldGroupArr,$groupConfig,$robGuildIdStart,0,count($goldGroupArr),GameConst::UNION_COMPETITION_GOLD);
            $newSilverStructure = $this->randomGroup($silverGroupArr,$groupConfig,$robGuildIdStart,$newGoldStructure['hasLast'],count($silverGroupArr),GameConst::UNION_COMPETITION_SILVER);
            error_log('******初始化【青铜】开始******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            $newBronzeStructure = $this->createDataByQuality($bronzeGroupArr,$groupConfig,$robGuildIdStart,$newSilverStructure['hasLast'],count($bronzeGroupArr),$nextStartTime,$endTime,GameConst::UNION_COMPETITION_BRONZE);
            error_log('******初始化【青铜】结束******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            if (empty($newBronzeStructure) || !$newBronzeStructure || $newBronzeStructure == null){
                error_log('******初始化青铜分组为空！！！！******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                return;
            }

            $this->newCreateOrUpdateLibrary(GameConst::UNION_COMPETITION_BRONZE,$newBronzeStructure['guildGroupData'],$nextStartTime,$endTime);
        }
        error_log('******青铜初始化结束！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');

        $testTime2 = time();
        error_log('******青铜初始化结束时间：'.$testTime2.'***准确时间:'.date("Y-m-d H:i:s",$testTime2)."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        error_log('******青铜初始化使用时间：'.($testTime2-$testTime1).'秒'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');

        return;
    }

    /**
     * 准备数据生成白银
     */
    public function prepareDataGeneration2()
    {
        $testTime1 = time();
        error_log('******白银初始化时间：'.$testTime1.'***准确时间:'.date("Y-m-d H:i:s",$testTime1)."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
        if ($isOpen != 1){
            error_log('******社团竞赛系统没有开启！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }

        error_log('******白银初始化开始！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        //获取当前请求时间
        $serverTime = GameService::get()->getReqTime();
        //获取当前时间属于周几
        $weekDay = date("w",$serverTime);
        error_log('******星期'.$weekDay."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        //获取工会公用分组配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            error_log('******杂项配置表不存在******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }

        //获取当前时间属于周几
        $hour = (int)date("H",$serverTime);
        //验证开启时段正确
        if ($weekDay != $groupConfig['matchTime1']){
            error_log('******白银初始化在每周3执行******timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }
        if ($weekDay == $groupConfig['matchTime1'] && $hour != 11){
            error_log('******白银初始化只会在每周3上午11点45执行******timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }

        //获取服务器所有的工会进行分组
        $serversConfigs = SzConfig::get()->loadAppConfig('database', 'MySql');
        $instance = new SzMySqlDb($serversConfigs[0]);
        $originalGuildArr = $instance->select("SELECT `id`  FROM `ft_guild_info` WHERE `num` >= ".$groupConfig['buddyNum']);
        $guildArr = array();
        if (!empty($originalGuildArr)){
            foreach ($originalGuildArr as $k=>$data){
                $guildArr[] = $data['id'];
            }
        }

        $guildsNum = count($guildArr);
        error_log('******公会数量为:'.$guildsNum."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        if (empty($guildArr) || $guildsNum == 0){
            error_log('******公会数量为0'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }

        //  正式的时候需要开启
        $nextStartTime = $serverTime + 10*60 - 1;
        //数据结构准备
        $robGuildIdStart = 1;//机器人工会id，之后需要转换为负数以作区分
        $endTime = $nextStartTime + $groupConfig['matchTime2'];//当前赛事失效时间

        $flag = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SILVER_FLAG);
        if ($flag == 1){//数据已经生成
            error_log('******白银已经生成！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }
        else{//非首次开启社团竞赛
            //晋级名额及降级名额
            $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_SILVER_FLAG,1);
//                $up = $groupConfig['promotion'][0];
//                $down = $groupConfig['promotion'][1];

            $gup = $groupConfig['goldPromotion'][0];
            $gdown = $groupConfig['goldPromotion'][1];
            $sup = $groupConfig['silverPromotion'][0];
            $sdown = $groupConfig['silverPromotion'][1];
            $bup = $groupConfig['copperPromotion'][0];
            $bdown = $groupConfig['copperPromotion'][1];
            /**
             * @var GuildCompetitionLibraryVo $goldLibraryInfo
             * @var GuildCompetitionLibraryVo $silverLibraryInfo
             * @var GuildCompetitionLibraryVo $bronzeLibraryInfo
             */
            $goldLibraryInfo =  SzPersister::get()->getVo(GameConst::UNION_COMPETITION_GOLD, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);
            $silverLibraryInfo =  SzPersister::get()->getVo(GameConst::UNION_COMPETITION_SILVER, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);
            $bronzeLibraryInfo =  SzPersister::get()->getVo(GameConst::UNION_COMPETITION_BRONZE, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);

            /**
             * @var GuildCompetitionBackVo $goldBackInfo
             * @var GuildCompetitionBackVo $silverBackInfo
             * @var GuildCompetitionBackVo $bronzeBackInfo
             */
            $goldBackInfo = SzPersister::get()->getVo(GameConst::UNION_COMPETITION_GOLD, GameConst::ORM_NAME_UNION_COMPETITION_BACKUPS);
            $silverBackInfo = SzPersister::get()->getVo(GameConst::UNION_COMPETITION_SILVER, GameConst::ORM_NAME_UNION_COMPETITION_BACKUPS);
            $bronzeBackInfo = SzPersister::get()->getVo(GameConst::UNION_COMPETITION_BRONZE, GameConst::ORM_NAME_UNION_COMPETITION_BACKUPS);

            if (!$goldLibraryInfo || !$silverLibraryInfo || !$bronzeLibraryInfo){
                error_log('******工会分组库丢失:******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                return;
            }
            if (!$silverBackInfo){
                error_log('******工会分组备份库丢失:******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                return;
            }

            //黄金小组调整
            $goldPreGuildArr = $this->shuntGroup($goldBackInfo,$gup,$gdown,$groupConfig,GameConst::UNION_COMPETITION_GOLD);
            //白银小组调整
            $silverPreGuildArr = $this->shuntGroup($silverBackInfo,$sup,$sdown,$groupConfig,GameConst::UNION_COMPETITION_SILVER);
            //青铜小组调整
            $bronzePreGuildArr = $this->shuntGroup($bronzeBackInfo,$bup,$bdown,$groupConfig,GameConst::UNION_COMPETITION_BRONZE);

            //进行工会重组
            if (!empty($silverPreGuildArr['toGold'])){//黄金赛事
                $goldGroupArr = array_merge($goldPreGuildArr['left'],$silverPreGuildArr['toGold']);
            }
            else{
                $goldGroupArr = $goldPreGuildArr['left'];
            }

            if (empty($goldPreGuildArr['toSilver']) && empty($bronzePreGuildArr['toSilver'])){//白银赛事
                $silverGroupArr = $silverPreGuildArr['left'];
            }
            else{
                $temp = array_merge($silverPreGuildArr['left'],$goldPreGuildArr['toSilver']);
                $silverGroupArr = array_merge($temp,$bronzePreGuildArr['toSilver']);
            }

            if (!empty($silverPreGuildArr['toBronze'])){//青铜赛事
                $bronzeGroupArr = array_merge($bronzePreGuildArr['left'],$silverPreGuildArr['toBronze']);
            }
            else{
                $bronzeGroupArr = $bronzePreGuildArr['left'];
            }

            //新参加的社团添加到青铜模块
            foreach ($guildArr as $key=>$value){
                if (!in_array($value,$goldGroupArr) && !in_array($value,$silverGroupArr) && !in_array($value,$bronzeGroupArr)){
                    $bronzeGroupArr[] = $value;
                }
            }

            if (empty($goldGroupArr)){
                error_log('******黄金分组库为空******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                return;
            }
            if (empty($silverGroupArr)){
                error_log('******白银分组库为空******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                return;
            }
            if (empty($bronzeGroupArr)){
                error_log('******青铜分组库为空******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                return;
            }

            $newGoldStructure = $this->randomGroup($goldGroupArr,$groupConfig,$robGuildIdStart,0,count($goldGroupArr),GameConst::UNION_COMPETITION_GOLD);
            error_log('******初始化【白银】开始******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            $newSilverStructure = $this->createDataByQuality($silverGroupArr,$groupConfig,$robGuildIdStart,$newGoldStructure['hasLast'],count($silverGroupArr),$nextStartTime,$endTime,GameConst::UNION_COMPETITION_SILVER);
            error_log('******初始化【白银】结束******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            if (empty($newSilverStructure) || !$newSilverStructure || $newSilverStructure == null){
                error_log('******初始化白银分组为空！！！！******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                return;
            }

            $this->newCreateOrUpdateLibrary(GameConst::UNION_COMPETITION_SILVER,$newSilverStructure['guildGroupData'],$nextStartTime,$endTime);
        }
        error_log('******白银初始化结束！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');

        $testTime2 = time();
        error_log('******白银初始化结束时间：'.$testTime2.'***准确时间:'.date("Y-m-d H:i:s",$testTime2)."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        error_log('******白银初始化使用时间：'.($testTime2-$testTime1).'秒'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');

        return;
    }

    /**
     * 准备数据生成黄金
     */
    public function prepareDataGeneration3()
    {
        $testTime1 = time();
        error_log('******社团赛黄金初始化开始：'.$testTime1.'***准确时间:'.date("Y-m-d H:i:s",$testTime1)."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
        if ($isOpen != 1){
            error_log('******社团竞赛系统没有开启！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }

        error_log('******黄金初始化开始！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        //获取当前请求时间
        $serverTime = GameService::get()->getReqTime();
        //获取当前时间属于周几
        $weekDay = date("w",$serverTime);
        error_log('******星期'.$weekDay."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        //获取工会公用分组配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            error_log('******杂项配置表不存在******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }

        //获取当前时间属于周几
        $hour = (int)date("H",$serverTime);
        //验证开启时段
        if ($weekDay != $groupConfig['matchTime1']){
            error_log('******黄金初始化在每周3执行******timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }
        if ($weekDay == $groupConfig['matchTime1'] && $hour != 11){
            error_log('******黄金初始化只在每周3上午11点40执行******timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }

        //获取服务器所有的工会进行分组
        $serversConfigs = SzConfig::get()->loadAppConfig('database', 'MySql');
        $instance = new SzMySqlDb($serversConfigs[0]);
        $originalGuildArr = $instance->select("SELECT `id`  FROM `ft_guild_info` WHERE `num` >= ".$groupConfig['buddyNum']);
        $guildArr = array();
        if (!empty($originalGuildArr)){
            foreach ($originalGuildArr as $k=>$data){
                $guildArr[] = $data['id'];
            }
        }

        $guildsNum = count($guildArr);
        error_log('******公会数量为:'.$guildsNum."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        if (empty($guildArr) || $guildsNum == 0){
            error_log('******公会数量为0'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            return;
        }
        //验证是否为首次社团竞赛
        $hasFirst = $redisDb->get(GameConst::CACHE_KEY_HAS_FIRST_UNION_COMPETITION);
        $nextStartTime = $serverTime + 15*60 - 1;
        //数据结构准备
        $robGuildIdStart = 1;//机器人工会id，之后需要转换为负数以作区分
        $endTime = $nextStartTime + $groupConfig['matchTime2'];//当前赛事失效时间

        //设置各阶段时间
        $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_START_TIME,$nextStartTime);
        $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_END_TIME,$endTime);
        $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_SUSPENSION_TIME,$endTime - 86400 - 86400);
        $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_SETTLEMENT_TIME,$endTime - 3600);

        if ($hasFirst != 1){//首次开启社团竞赛
            error_log('******首次开启！！！全部生成为银'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
            //设置已经举办了第一次社团竞赛标记
            $redisDb->set(GameConst::CACHE_KEY_HAS_FIRST_UNION_COMPETITION,1);
            $newStructureGuilds = $this->createDataByQuality($guildArr,$groupConfig,$robGuildIdStart,1,$guildsNum,$nextStartTime,$endTime,GameConst::UNION_COMPETITION_SILVER);
            $this->createOrUpdateLibrary(array(array(),$newStructureGuilds['guildGroupData'],array()),$serverTime,$endTime);

            //设置所有品质数据生成成功
            $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_GOLD_FLAG,1);
            $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_SILVER_FLAG,1);
            $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_BRONZE_FLAG,1);
        }
        else{//非首次开启社团竞赛
            $flag = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_GOLD_FLAG);
            if ($flag == 1){//数据已经生成
                error_log('******黄金已经生成！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                return;
            }
            else{
                //晋级名额及降级名额
//                $up = $groupConfig['promotion'][0];
//                $down = $groupConfig['promotion'][1];

                $gup = $groupConfig['goldPromotion'][0];
                $gdown = $groupConfig['goldPromotion'][1];
                $sup = $groupConfig['silverPromotion'][0];
                $sdown = $groupConfig['silverPromotion'][1];
                $bup = $groupConfig['copperPromotion'][0];
                $bdown = $groupConfig['copperPromotion'][1];

                $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_GOLD_FLAG,1);
                /**
                 * @var GuildCompetitionLibraryVo $goldLibraryInfo
                 * @var GuildCompetitionLibraryVo $silverLibraryInfo
                 * @var GuildCompetitionLibraryVo $bronzeLibraryInfo
                 */
                $goldLibraryInfo =  SzPersister::get()->getVo(GameConst::UNION_COMPETITION_GOLD, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);
                $silverLibraryInfo =  SzPersister::get()->getVo(GameConst::UNION_COMPETITION_SILVER, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);
                $bronzeLibraryInfo =  SzPersister::get()->getVo(GameConst::UNION_COMPETITION_BRONZE, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);

                /**
                 * @var GuildCompetitionBackVo $goldBackInfo
                 * @var GuildCompetitionBackVo $silverBackInfo
                 * @var GuildCompetitionBackVo $bronzeBackInfo
                 */
                $goldBackInfo = SzPersister::get()->getVo(GameConst::UNION_COMPETITION_GOLD, GameConst::ORM_NAME_UNION_COMPETITION_BACKUPS);
                $silverBackInfo = SzPersister::get()->getVo(GameConst::UNION_COMPETITION_SILVER, GameConst::ORM_NAME_UNION_COMPETITION_BACKUPS);
                $bronzeBackInfo = SzPersister::get()->getVo(GameConst::UNION_COMPETITION_BRONZE, GameConst::ORM_NAME_UNION_COMPETITION_BACKUPS);

                if (!$goldLibraryInfo || !$silverLibraryInfo || !$bronzeLibraryInfo){
                    error_log('******工会分组库数据丢失******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                    return;
                }

                //黄金小组调整
                $goldPreGuildArr = $this->shuntGroup($goldBackInfo,$gup,$gdown,$groupConfig,GameConst::UNION_COMPETITION_GOLD);
                //白银小组调整
                $silverPreGuildArr = $this->shuntGroup($silverBackInfo,$sup,$sdown,$groupConfig,GameConst::UNION_COMPETITION_SILVER);
                //青铜小组调整
                $bronzePreGuildArr = $this->shuntGroup($bronzeBackInfo,$bup,$bdown,$groupConfig,GameConst::UNION_COMPETITION_BRONZE);

                //进行工会重组
                if (!empty($silverPreGuildArr['toGold'])){//黄金赛事
                    $goldGroupArr = array_merge($goldPreGuildArr['left'],$silverPreGuildArr['toGold']);
                }
                else{
                    $goldGroupArr = $goldPreGuildArr['left'];
                }

                if (empty($goldPreGuildArr['toSilver']) && empty($bronzePreGuildArr['toSilver'])){//白银赛事
                    $silverGroupArr = $silverPreGuildArr['left'];
                }
                else{
                    $temp = array_merge($silverPreGuildArr['left'],$goldPreGuildArr['toSilver']);
                    $silverGroupArr = array_merge($temp,$bronzePreGuildArr['toSilver']);
                }

                if (!empty($silverPreGuildArr['toBronze'])){//青铜赛事
                    $bronzeGroupArr = array_merge($bronzePreGuildArr['left'],$silverPreGuildArr['toBronze']);
                }
                else{
                    $bronzeGroupArr = $bronzePreGuildArr['left'];
                }

                //新参加的社团添加到青铜模块
                foreach ($guildArr as $key=>$value){
                    if (!in_array($value,$goldGroupArr) && !in_array($value,$silverGroupArr) && !in_array($value,$bronzeGroupArr)){
                        $bronzeGroupArr[] = $value;
                    }
                }

                if (empty($goldGroupArr)){
                    error_log('******黄金分组库为空******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                    return;
                }
                if (empty($silverGroupArr)){
                    error_log('******白银分组库为空******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                    return;
                }
                if (empty($bronzeGroupArr)){
                    error_log('******青铜分组库为空******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                    return;
                }

                error_log('******初始化【黄金】开始******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                $newGoldStructure = $this->createDataByQuality($goldGroupArr,$groupConfig,$robGuildIdStart,0,count($goldGroupArr),$nextStartTime,$endTime,GameConst::UNION_COMPETITION_GOLD);
                error_log('******初始化【黄金】结束******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                if (empty($newGoldStructure) || !$newGoldStructure || $newGoldStructure == null){
                    error_log('******初始化黄金分组为空！！！！******'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
                    return;
                }

                $this->newCreateOrUpdateLibrary(GameConst::UNION_COMPETITION_GOLD,$newGoldStructure['guildGroupData'],$nextStartTime,$endTime);
            }
        }
        error_log('******黄金初始化结束！！！'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');

        $testTime2 = time();
        error_log('******黄金初始化结束时间：'.$testTime2.'***准确时间:'.date("Y-m-d H:i:s",$testTime2)."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        error_log('******黄金初始化使用时间：'.($testTime2-$testTime1).'秒'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');

        return;
    }

    /**
     * 设置工会竞赛库单独
     * @param $quality
     * @param $group
     * @param $serverTime
     * @param $endTime
     * @throws SzException
     */
    public function newCreateOrUpdateLibrary($quality,$group,$serverTime,$endTime){
        error_log('******设置工会竞赛库开始！！！！:'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
        //进行赛事品质组入库
        /**
         * @var GuildCompetitionLibraryVo $guildCompetitionLibraryInfo
         */
        $makeString = '';
        //工会组数据结构调整
        if (!empty($group)){
            foreach ($group as $gid=>$guilds){
                if ($makeString == ''){
                    $makeString = ($gid+1).':'.implode(',',$guilds);

                }
                else{
                    $makeString = $makeString.';'.($gid+1).':'.implode(',',$guilds);
                }
            }
        }
        $guildCompetitionLibraryInfo = SzPersister::get()->getVo($quality, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);
        if (!$guildCompetitionLibraryInfo){
            $guildCompetitionLibraryInfo = new GuildCompetitionLibraryVo(
                $quality,
                $makeString,
                $serverTime,
                $serverTime,
                $endTime,
                true
            );
        }
        else{
            $guildCompetitionLibraryInfo->setGuildsByGroup($makeString);
            $guildCompetitionLibraryInfo->setUpdateTime($serverTime);
            $guildCompetitionLibraryInfo->setEndTime($endTime);
        }

        //更新数据
        SzPersister::get()->setVo($guildCompetitionLibraryInfo);
        error_log('******设置工会竞赛库结束！！！！:'."\r\n",3,$_ENV['LOG_ROOT'].'/UnionCompetition-' . date('Y-m-d') . '.log');
    }

    /**
     * 数据记录黄金
     * @throws SzException
     */
    public function saveGuildByGroupData3()
    {
        $testTime1 = time();
        error_log('******上届黄金记录开始：'.$testTime1.'***准确时间:'.date("Y-m-d H:i:s",$testTime1)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
        if ($isOpen != 1){
            error_log('******社团竞赛系统没有开启！！！'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            return;
        }

        //获取杂项配置表配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            error_log('******杂项配置表不存在******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            return;
        }

        //获取当前请求时间
        $serverTime = GameService::get()->getReqTime();
        //获取当前时间属于周几
        $weekDay = date("w",$serverTime);
        //获取当前时间属于周几
        $hour = (int)date("H",time());
        //正式的时候需要开启
        if ($weekDay != $groupConfig['matchTime1']){
            error_log('******上届黄金记录只会在周3执行******timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            return;
        }
        if ($weekDay == $groupConfig['matchTime1'] && $hour != 11){
            error_log('******上届黄金记录只会在周3上午11点5分执行******timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            return;
        }

        //获取今天凌晨的时间戳
        $toDayStartTime = strtotime(date('Y-m-d'));
        $rangeTime1 = $toDayStartTime + $hour*3600 + 5*60 - 60;
        $rangeTime2 = $toDayStartTime + $hour*3600 + 5*60 + 60;

        if ($serverTime > $rangeTime1 && $serverTime < $rangeTime2) {
            //黄金品质结算
            $goldSuc = $this->newGuildRecordUpdateOrCreate(GameConst::UNION_COMPETITION_GOLD,$serverTime);
            error_log('******黄金记录结果:【'.$goldSuc.'】'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            error_log('******上届黄金记录结束！！！'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
        }
        else{
            error_log('******上届黄金记录超时！！！'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
        }

        //清理各品质数据生成标记
        $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_GOLD_FLAG,0);

        $testTime2 = time();
        error_log('******上届黄金记录结束时间：'.$testTime2.'***准确时间:'.date("Y-m-d H:i:s",$testTime2)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
        error_log('******上届黄金记录使用时间：'.($testTime2-$testTime1).'秒'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');

        return;
    }

    /**
     * 数据记录白银
     * @throws SzException
     */
    public function saveGuildByGroupData2()
    {
        $testTime1 = time();
        error_log('******上届白银记录开始：'.$testTime1.'***准确时间:'.date("Y-m-d H:i:s",$testTime1)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
        if ($isOpen != 1){
            error_log('******社团竞赛系统没有开启！！！'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            return;
        }

        //获取杂项配置表配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            error_log('******杂项配置表不存在******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            return;
        }

        //获取当前请求时间
        $serverTime = GameService::get()->getReqTime();
        //获取当前时间属于周几
        $weekDay = date("w",$serverTime);
        //获取当前时间属于周几
        $hour = (int)date("H",time());
        //正式的时候需要开启
        if ($weekDay != $groupConfig['matchTime1']){
            error_log('******上届白银记录只会在周3执行******timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            return;
        }
        if ($weekDay == $groupConfig['matchTime1'] && $hour != 11){
            error_log('******上届白银数据记录只会在周3上午11点10分执行******timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            return;
        }

        //获取今天凌晨的时间戳
        $toDayStartTime = strtotime(date('Y-m-d'));
        $rangeTime1 = $toDayStartTime + $hour*3600 + 10*60 - 60;
        $rangeTime2 = $toDayStartTime + $hour*3600 + 10*60 + 60;

        if ($serverTime > $rangeTime1 && $serverTime < $rangeTime2) {
            //白银品质结算
            $silverSuc = $this->newGuildRecordUpdateOrCreate(GameConst::UNION_COMPETITION_SILVER,$serverTime);
            error_log('******白银记录结果:【'.$silverSuc.'】'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            error_log('******上届白银记录结束！！！'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
        }
        else{
            error_log('******上届白银记录超时！！！'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
        }

        //清理各品质数据生成标记
        $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_SILVER_FLAG,0);

        $testTime2 = time();
        error_log('******上届白银记录结束时间：'.$testTime2.'***准确时间:'.date("Y-m-d H:i:s",$testTime2)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
        error_log('******上届白银记录使用时间：'.($testTime2-$testTime1).'秒'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');

        return;
    }

    /**
     * 数据记录青铜
     * @throws SzException
     */
    public function saveGuildByGroupData1()
    {
        $testTime1 = time();
        error_log('******上届青铜记录开始：'.$testTime1.'***准确时间:'.date("Y-m-d H:i:s",$testTime1)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');

        //验证社团竞赛系统是否开启
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        $isOpen = $redisDb->get(GameConst::CACHE_KEY_UNION_COMPETITION_SWITCH);
        if ($isOpen != 1){
            error_log('******社团竞赛系统没有开启！！！'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            return;
        }

        //获取杂项配置表配置
        $groupConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_UNION_COMPETITION_OTHERS, 1, true);
        if (!$groupConfig || empty($groupConfig)){
            error_log('******杂项配置表不存在******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            return;
        }

        //获取当前请求时间
        $serverTime = GameService::get()->getReqTime();
        //获取当前时间属于周几
        $weekDay = date("w",$serverTime);
        //获取当前时间属于周几
        $hour = (int)date("H",time());
        //正式的时候需要开启
        if ($weekDay != $groupConfig['matchTime1']){
            error_log('******上届青铜数据记录只会在周3执行******timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            return;
        }
        if ($weekDay == $groupConfig['matchTime1'] && $hour != 11){
            error_log('******上届青铜记录只会在周3中午11点15分执行******timeStamp:'.$serverTime.'***准确时间:'.date("Y-m-d H:i:s",$serverTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            return;
        }

        //获取今天凌晨的时间戳
        $toDayStartTime = strtotime(date('Y-m-d'));
        $rangeTime1 = $toDayStartTime + $hour*3600 + 15*60 - 60;
        $rangeTime2 = $toDayStartTime + $hour*3600 + 15*60 + 60;

        if ($serverTime > $rangeTime1 && $serverTime < $rangeTime2) {
            //青铜品质结算
            $bronzeSuc = $this->newGuildRecordUpdateOrCreate(GameConst::UNION_COMPETITION_BRONZE,$serverTime);
            error_log('******青铜记录结果:【'.$bronzeSuc.'】'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            error_log('******上届青铜记录结束！！！'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
        }
        else{
            error_log('******上届青铜记录超时！！！'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
        }

        //清理各品质数据生成标记
        $redisDb->set(GameConst::CACHE_KEY_UNION_COMPETITION_BRONZE_FLAG,0);

        $testTime2 = time();
        error_log('******上届青铜记录结束时间：'.$testTime2.'***准确时间:'.date("Y-m-d H:i:s",$testTime2)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
        error_log('******上届青铜记录使用时间：'.($testTime2-$testTime1).'秒'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');

        return;
    }

    /**
     * 历史记录数据更新或者创建
     * @param $quality
     * @param $reqTime
     * @return bool
     * @throws SzException
     */
    public function newGuildRecordUpdateOrCreate($quality,$reqTime){
        error_log('******上一届数据记录*****品质赛事为:【'.$quality.'】的数据开始！！！！******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
        /**
         * @var GuildCompetitionLibraryVo $libraryInfo
         */
        //获取本届各品质赛事参与的工会
        $libraryInfo = SzPersister::get()->getVo($quality, GameConst::ORM_NAME_UNION_COMPETITION_LIBRARY);
        $sortString = '';
        if ($libraryInfo){
            if ($libraryInfo->getGuildsByGroup() != ''){
                $guildStrArr = explode(';',$libraryInfo->getGuildsByGroup());
                foreach ($guildStrArr as $key=>$groupStr){
                    $guildScoreArr = array();
                    $guildsArr = explode(',',(explode(':',$groupStr)[1]));
                    $groupId = explode(':',$groupStr)[0];
                    if (!empty($guildsArr)){
                        foreach ($guildsArr as $key1=>$guildId){
                            //获取工会工会数据
                            /**
                             * @var GuildCompetitionVo $guildCompetitionData
                             */
                            $guildCompetitionData = SzPersister::get()->getVo($guildId, GameConst::ORM_NAME_UNION_COMPETITION_COMMON_DATA);
                            if (!$guildCompetitionData){
                                error_log('******社团ID为:【'.$guildId.'】------公共数据为空******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
                                $point = 0;
                                $person = 0;
                                $flagNum = 0;
                            }
                            else{
                                $point = $guildCompetitionData->getPoint();
                                $flagNum = $guildCompetitionData->getFlags();
                                if (json_decode($guildCompetitionData->getParticipant()) != ''){
                                    $person = count(explode(',',json_decode($guildCompetitionData->getParticipant())));
                                }
                                else{
                                    $person = 0;
                                }
                            }
                            $guildScoreArr[$key1]['gid'] = $guildId;
                            $guildScoreArr[$key1]['score'] = $point;
                            $guildScoreArr[$key1]['personNum'] = $person;
                            $guildScoreArr[$key1]['flags'] = $flagNum;
                        }

                        //历史数据进行更新
                        $scoreTemp = array();
                        if (!empty($guildScoreArr) && count($guildScoreArr) != 0){
                            error_log('******小组ID为:【'.$groupId.'】------历史数据开始建立或者更新******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
                            //对分数数组进行排序
                            foreach ($guildScoreArr as $k => $row) {
                                $scoreTemp[$k] = $row['score'];
                            }
                            array_multisort($scoreTemp, SORT_DESC, $guildScoreArr);

                            $gidStr = '';
                            $gold = '';
                            $silver = '';
                            $bronze = '';
                            $i = 1;
                            $create = false;
                            $update = false;
                            foreach ($guildScoreArr as $index=>$guildRecordData) {
                                //小组排名字符串制作
                                if ($gidStr == ''){
                                    $gidStr = $guildRecordData['gid'];
                                }
                                else{
                                    $gidStr = $gidStr.','.$guildRecordData['gid'];
                                }

                                //真实用户数据处理
                                if ($guildRecordData['gid'] > 0){
                                    //历史数据存储
                                    $scoreArr = array(1=>0,2=>0,3=>0);
                                    /**
                                     * @var GuildCompetitionHistoryVo $guildHistoryInfo
                                     */
                                    $guildHistoryInfo = SzPersister::get()->getVo($guildRecordData['gid'], GameConst::ORM_NAME_UNION_COMPETITION_HISTORY);
                                    if (!$guildHistoryInfo){
                                        error_log('******创建工会ID为:【'.$guildRecordData['gid'].'】的历史数据开始******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
                                        if ($i <= 3) {//排名前三的工会记录排名数据
                                            if ($quality == GameConst::UNION_COMPETITION_GOLD){
                                                $scoreArr[$i] = 1;
                                                $gold = implode(',',$scoreArr);
                                            }
                                            if ($quality == GameConst::UNION_COMPETITION_SILVER){
                                                $scoreArr[$i] =1;
                                                $silver = implode(',',$scoreArr);
                                            }
                                            if ($quality == GameConst::UNION_COMPETITION_BRONZE){
                                                $scoreArr[$i] =1;
                                                $bronze = implode(',',$scoreArr);
                                            }
                                        }
                                        else{
                                            $gold = $silver = $bronze = implode(',',array(1=>0,2=>0,3=>0));
                                        }

                                        $guildHistoryInfo = new GuildCompetitionHistoryVo(
                                            $guildRecordData['gid'],
                                            json_encode($gold),
                                            json_encode($silver),
                                            json_encode($bronze),
                                            $guildRecordData['score'],
                                            $reqTime,
                                            $reqTime,
                                            0,
                                            true
                                        );
                                        $create = true;
                                    }
                                    else{
                                        error_log('******更新工会ID为:【'.$guildRecordData['gid'].'】的历史数据开始******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
                                        if ($i <= 3) {//排名前三的工会记录排名数据
                                            if ($quality == GameConst::UNION_COMPETITION_GOLD){
                                                $temp = json_decode($guildHistoryInfo->getGold());
                                                if ($temp != ''){
                                                    $goldArr = explode(',',$temp);
                                                    $goldArr[$i - 1] = $goldArr[$i - 1] + 1;
                                                }
                                                else{
                                                    $scoreArr[$i] = 1;
                                                    $goldArr = $scoreArr;
                                                }
                                                $guildHistoryInfo->setGold(implode(',',$goldArr));
                                            }
                                            if ($quality == GameConst::UNION_COMPETITION_SILVER){
                                                $temp = json_decode($guildHistoryInfo->getSilver());
                                                if ($temp != ''){
                                                    $silverArr = explode(',',$temp);
                                                    $silverArr[$i - 1] = $silverArr[$i - 1] + 1;
                                                }
                                                else{
                                                    $scoreArr[$i] = 1;
                                                    $silverArr = $scoreArr;
                                                }
                                                $guildHistoryInfo->setSilver(implode(',',$silverArr));
                                            }
                                            if ($quality == GameConst::UNION_COMPETITION_BRONZE){
                                                $temp = json_decode($guildHistoryInfo->getBronze());
                                                if ($temp != ''){
                                                    $bronzeArr = explode(',',$temp);
                                                    $bronzeArr[$i - 1] = $bronzeArr[$i - 1] + 1;
                                                }
                                                else{
                                                    $scoreArr[$i] = 1;
                                                    $bronzeArr = $scoreArr;
                                                }
                                                $guildHistoryInfo->setBronze(implode(',',$bronzeArr));
                                            }
                                        }

                                        if ($guildHistoryInfo->getHighest() < $guildRecordData['score']){
                                            $guildHistoryInfo->setHighest($guildRecordData['score']);
                                        }
                                        $guildHistoryInfo->setUpdateTime($reqTime);
                                        $update = true;
                                    }
                                    SzPersister::get()->setVo($guildHistoryInfo);
                                    if ($create){
                                        error_log('******创建工会ID为:【'.$guildRecordData['gid'].'】的历史数据结束******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
                                    }
                                    if ($update){
                                        error_log('******更新工会ID为:【'.$guildRecordData['gid'].'】的历史数据结束******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
                                    }

                                    //创建工会的记录数据
                                    /**
                                     * @var GuildCompetitionRecordVo $guildRecord
                                     */
                                    $guildRecord = SzPersister::get()->getVo($guildRecordData['gid'], GameConst::ORM_NAME_UNION_COMPETITION_RECORD);
                                    if (!$guildRecord){
                                        $guildRecord = new GuildCompetitionRecordVo(
                                            $guildRecordData['gid'],
                                            $groupId,
                                            $quality,
                                            (int)date('Ymd',$reqTime),
                                            (int)date('Ymd',$reqTime),
                                            $guildRecordData['score'],
                                            $i,
                                            $guildRecordData['personNum'],
                                            1,
                                            $reqTime,
                                            $reqTime,
                                            true
                                        );
                                        error_log('******成功创建小组--【group】:'.($groupId).'---真实玩家工会ID:'.$guildRecordData['gid'].'】的记录数据-----*******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
                                    }
                                    else{
                                        $guildRecord->setGroupId($groupId);
                                        $guildRecord->setQuality($quality);
                                        $guildRecord->setInitializationData($guildRecord->getSettlement());
                                        $guildRecord->setSettlement((int)date('Ymd',$reqTime));
                                        $guildRecord->setLastPoint($guildRecordData['score']);
                                        $guildRecord->setRank($i);
                                        $guildRecord->setNumber($guildRecordData['personNum']);
                                        $guildRecord->setIsFirst(0);
                                        $guildRecord->setUpdateTime($reqTime);
                                    }
                                    SzPersister::get()->setVo($guildRecord);

//                                //社团竞赛数据埋点
//                                StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $reqTime, array(
//                                    'clientData' => array(
//                                        'tid' => 'Module:unionCompetition|action:getQuality|',
//                                        'item' => $guildRecordData['gid'].'&'.$quality,
//                                        'value' => 1
//                                    )
//                                ));
//                                StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $reqTime, array(
//                                    'clientData' => array(
//                                        'tid' => 'Module:unionCompetition|action:getTotalPoint|',
//                                        'item' => $guildRecordData['gid'].'&'.$guildRecordData['score'],
//                                        'value' => 1
//                                    )
//                                ));
//                                StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $reqTime, array(
//                                    'clientData' => array(
//                                        'tid' => 'Module:unionCompetition|action:getTotalFlag|',
//                                        'item' => $guildRecordData['gid'].'&'.$guildRecordData['flags'],
//                                        'value' => 1
//                                    )
//                                ));
//                                StatisticsService::get()->saveGuildLog(GameConst::LOG_TYPE_USER_STATUS, $reqTime, array(
//                                    'clientData' => array(
//                                        'tid' => 'Module:unionCompetition|action:getTotalNum|',
//                                        'item' => $guildRecordData['gid'].'&'.$guildRecordData['personNum'],
//                                        'value' => 1
//                                    )
//                                ));
                                }

                                $i++;
                            }

                            if ($sortString == ''){
                                $sortString = $groupId.':'.$gidStr;
                            }
                            else{
                                $sortString = $sortString.';'.$groupId.':'.$gidStr;
                            }

                            error_log('******小组ID为:【'.$groupId.'】------历史数据结束建立或者更新******'.$reqTime.'***准确时间:'.date("Y-m-d H:i:s",$reqTime)."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
                        }
                    }
                }

                //新排序字符串进行更新
                if ($sortString != ''){
                    $libraryInfo->setGuildsByGroup($sortString);
                }
                $libraryInfo->setUpdateTime($reqTime);
                SzPersister::get()->setVo($libraryInfo);

                //新排序字符串进行备份更新
                /**
                 * @var GuildCompetitionBackVo $backInfo
                 */
                $backInfo = SzPersister::get()->getVo($quality, GameConst::ORM_NAME_UNION_COMPETITION_BACKUPS);
                if ($backInfo){
                    if ($sortString != ''){
                        $backInfo->setGuildsByGroup($sortString);
                    }
                    $backInfo->setUpdateTime($reqTime);
                    $backInfo->setEndTime($reqTime + 45*60 - 1 + 604800);
                }
                else{
                    //创建新的备份
                    $backInfo = new GuildCompetitionBackVo(
                        $quality,
                        $sortString,
                        $reqTime,
                        $reqTime,
                        $reqTime + 55*60 - 1 + 604800,
                        true
                    );
                }
                SzPersister::get()->setVo($backInfo);
            }
            else{
                error_log('******社团竞赛数据结算*****品质赛事为:【'.$quality.'】的参与工会为空******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
            }
        }
        else{
            error_log('******社团竞赛数据结算*****品质赛事为:【'.$quality.'】的工会库不存在******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
        }

        error_log('******社团竞赛数据结算*****品质赛事为:【'.$quality.'】的数据结束！！！！******'."\r\n",3,$_ENV['LOG_ROOT'] . '/UnionCompetitionSaveData-' . date('Y-m-d') . '.log');
        return true;
    }

    /**
     * 验证玩家是否在本届社团赛离开公会
     * @param $userId
     * @param $guildId
     * @param $startTime
     * @param $endTime
     * @param $reqTime
     * @return int
     * @throws SzException
     */
    public function checkPlayer($userId,$guildId,$startTime,$endTime,$reqTime)
    {
        $code = 0;
        /**
         * @var $profileInfoList  ModuleProfileInfoVoList
         * @var ModuleProfileInfoVo $recordGuild
         */
        $profileInfoList = SzPersister::get()->getVoList($userId, ModuleProfileConst::ORM_NAME_PROFILE_INFO);
        //获取玩家的旧工会数据
        $recordGuild = $profileInfoList->getElement(GameConst::USER_INFO_TYPE_LAST_GUILD_MSG,false);

        if ($recordGuild) {
            $oldString = $recordGuild->getRawInfo();
            if ($oldString != ''){
                $oldData = explode(':',$oldString);
                $oldGuildId = $oldData[0];
                $oldQuitTime = $oldData[1];
                if ($oldGuildId != 0){
                    if ($oldQuitTime >= $startTime && $oldQuitTime <= $endTime){//在本届社团赛期间退出公会
                        if ($oldGuildId != $guildId){//换到其他工会
                             $code = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_119'];//在本届公会赛换到其他工会，无法进行相关操作
                        }
                        else{//退出又回到自己之前的工会
                            $code = 0;
                        }
                    }
                    elseif ($oldQuitTime > $endTime){//在错误时间退出公会
                        $code = GameConst::GUILD_MATCH_EXCEPTION_CODE_ARRAY['guildMatch_118'];// 操作违规，联系客服
                    }
                    else{//在本届社团赛之前退出公会
                        $code = 0;
                    }
                }
                else{
                    $code = 0;
                }
            }
        }

        return $code;
    }
}
